Habeeb Rahman Habeeb Rahman - 4 years ago 179
PHP Question

PHP string replace exclude string inside braces

$str = "PHP is a server-side {{scripting language}} designed for {{web development}} but also used as a general-purpose programming language";
$search = 'language';
$replace = 'english';

$new_str = str_replace($search, $replace, $str);


In the above code, how can we exclude the string inside {{ ... }}. such that the output should be

"PHP is a server-side {{scripting language}} designed for {{web development}} but also used as a general-purpose programming english"

Answer Source

Use preg_replace() instead of str_replace():

$pattern = sprintf('/{{[^}]+}}(*SKIP)(*F)|%s/', preg_quote($search, '/'));
$new_str = preg_replace($pattern, $replace, $str);

{{[^}]+}} matches the contents inside {{...}} block, (*SKIP)(*F) skips it, and %s (which is substituted with the escaped search string) matches the required word.

Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download