i.brod
i.brod

Reputation: 4603

PHP: Replace the content between two characters, in multiple occurrences

I'm trying to replace the contents between some "special" characters, in each of their occurrences. For example, let's say i have that string:

<div><small>static content</small><small>[special content type 3]</small> 
<small>static content</small><small>[special content type 4]</small></div>

I would like to replace each "special content", between square brackets, with something that is represented by this "identifier"(let's say, some "widget").

I've tried this code from Stackoverflow:

$search = "/[^<tag>](.*)[^<\/tag>]/";
$replace = "your new inner text";
$string = "<tag>i dont know what is here</tag>";
echo preg_replace($search,$replace,$string);

This works, but only for the first occurrence. I need this operation to be repeated across the entire string.

I've also tried this one:

echo preg_replace('/<div class="username">.+?</div>/im', '<div 
class="username">Special Username<\/div>', $string) ;

It gives me a "Warning: preg_replace(): Unknown modifier 'd' in Standard input code on line 8" error.

Any ideas?

Upvotes: 3

Views: 6430

Answers (2)

vasco.randolph
vasco.randolph

Reputation: 109

function replace_all_text_between($str, $start, $end, $replacement) {

    $replacement = $start . $replacement . $end;

    $start = preg_quote($start, '/');
    $end = preg_quote($end, '/');
    $regex = "/({$start})(.*?)({$end})/";

    return preg_replace($regex,$replacement,$str);
}

Upvotes: 2

Nick
Nick

Reputation: 147166

Your code from stackoverflow needs minor changes:

$search = "/(<tag>)(.*?)(<\/tag>)/";
$replace = '$1your new inner text$3';
$string = "<tag>i dont know what is here</tag> some text <tag>here's another one</tag>";
echo preg_replace($search,$replace,$string);

Upvotes: 2

Related Questions