Home > Back-end >  Find string between and replace with PHP
Find string between and replace with PHP

Time:12-29

I want to find and replace the string between the 2 sets of {{}}:

<p>I want to {{find}} this {{string}}.</p>

After I want to remove the {{}} and put the 2 strings in bold.

This is what I have tried:

$string = '<p>I want to {{find}} this {{string}}.</p>';
if(preg_match_all('/{{(.*?)}}/', $string, $matches) == 1) {
    foreach ($matches as $match) {
        echo '<b>'.$match.'</b>';
    }
}

CodePudding user response:

You can do this with preg_replace like this

$string = '<p>I want to {{find}} this {{string}}.</p>';
$replaced_string = preg_replace('/{{(.*?)}}/', '<b>$1</b>', $string);
echo $replaced_string;

Output

I want to find this string.

  • Related