Skip to content
Advertisement

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement