note 111755 added to function.preg-quote
| From: | php at richardneill dot org | Date: | Mon, 25 Mar 2013 22:40:36 +0000 |
| Subject: | note 111755 added to function.preg-quote | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-194198@lists.php.net to get a copy of this message | ||
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*
----
Server IP: 69.147.83.199
Probable Submitter: 87.194.171.29
----
Manual Page -- http://php.net/manual/en/function.preg-quote.php
Edit -- https://master.php.net/note/edit/111755
Del: integrated -- https://master.php.net/note/delete/111755/integrated
Del: useless -- https://master.php.net/note/delete/111755/useless
Del: bad code -- https://master.php.net/note/delete/111755/bad+code
Del: spam -- https://master.php.net/note/delete/111755/spam
Del: non-english -- https://master.php.net/note/delete/111755/non-english
Del: in docs -- https://master.php.net/note/delete/111755/in+docs
Del: other reasons-- https://master.php.net/note/delete/111755
Reject -- https://master.php.net/note/reject/111755
Search -- https://master.php.net/manage/user-notes.php