between Archives - wiki

PHP replace between

In this snippet I am just creating an useful function to replace string in between two string (including the given string )

The replace between function definition

 * function for replaceing sting between two string (included these two strings)
 * @param String $str_start <p>start string of search</p>
 * @param String $str_end <p>ending string of search</p>
 * @param String $replace <p>replace with</p>
 * @param String $string <p>source string (the original string we want to perform search)</p>
 * @return String
function replace_between($str_start, $str_end,  $replace, $source_string) {
    $startPos = strpos($source_string, $str_start);
    $endPos = strpos($source_string, $str_end);
    if ($startPos === false || $endPos === false) {
        return $source_string;

    $textToDelete = substr($source_string, $startPos, ($endPos + strlen($str_end)) - $startPos);

    return str_replace($textToDelete, $replace, $source_string);


sample function calls

sample 1

$mystring = '<div>a b c d e f g a x c </div>';

$new_str = replace_between('a', 'c',  'W', $mystring);

echo $new_str;


<div>W d e f g a x c </div>


sample 2

$mystring = '<div>some text <a href="">click me</a> </div>';

$new_str = replace_between('<a', '</a>',  '', $mystring);

echo $new_str;


<div>some text  </div>

Using preg_replace()

$mystring = '<div>abc def gaxc hiks dfess ddfsdfed </div>';

$new_str = preg_replace('/def[\s\S]+?dfess/', '', $mystring);

echo $new_str;


<div>abc  ddfsdfed </div>




By bm on June 24, 2016 | php | A comment?
Tags: , ,