3

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?

i.brod
  • 3,993
  • 11
  • 38
  • 74

2 Answers2

2

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);
Nick
  • 138,499
  • 22
  • 57
  • 95
2
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);
}
vasco.randolph
  • 109
  • 1
  • 2
  • 9