note 111755 deleted from function.preg-quote by peehaa
| From: | peehaa@php.net | Date: | Mon, 09 Dec 2013 11:42:40 +0000 |
| Subject: | note 111755 deleted from function.preg-quote by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197846@lists.php.net to get a copy of this message | ||
Note Submitter: php at richardneill dot org
----
preg_quote() only works on the search string, not the replacement string.
But the replacement string isn't always literal, as it can contain backreferences.
There's no function to quote the replacement string, but a workaround is to escape all $ and \
signs:
$replace = str_replace
(array('\\','$'),array('\\\\','\$'),$replace);
For example:
$text = 'Test: *#5*';
$search = "*#5*";
$replace = "*$5\\1*";
$search = preg_quote($search, "/");
$replace = str_replace
(array('\\','$'),array('\\\\','\$'),$replace);
$new = preg_replace("/$search/", "$replace", $text);
echo "Input: $text\nOutput: $new\n";
Prints:
Input: Test: *#5*
Output: Test: *$5\1*