Search code examples
phpregexpreg-replacepreg-match

PHP Preg_replace() pattern not work


I wan to replace text using preg_replace.But my search string have a / so it makes problem.

How can I solve it?

$search='r/trtrt';
echo preg_replace('/\b'.addslashes($search).'\b/', 'ERTY', 'TG FRT');

I am getting error preg_replace(): Unknown modifier 'T'


Solution

  • Use a different delimiter and don't use addslashes, that is escaping non-regex special characters (or a mix of regex and non-regex characters, I'd say the majority of the time dont use addslashes).

    $search='r/trtrt';
    echo preg_replace('~\b'. $search.'\b~', 'ERTY', 'TG FRT');
    

    You could use preg_quote as an alternative. Just changing the delimiter is the easiest solution though.