note 106263 deleted from function.preg-replace by crell
| From: | crell@php.net | Date: | Fri, 01 Jul 2022 19:48:01 +0000 |
| Subject: | note 106263 deleted from function.preg-replace by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218858@lists.php.net to get a copy of this message | ||
Note Submitter: akarmenia at gmail dot com
----
[Editor's note: in this case it would be wise to rely on the preg_quote() function instead
which was added for this specific purpose]
If your replacement string has a dollar sign or a backslash. it may turn into a backreference
accidentally! This will fix it.
I want to replace 'text' with '$12345' but this becomes a backreference to $12
(which doesn't exist) and then it prints the remaining '34'. The function down below
will return a string that escapes the backreferences.
OUTPUT:
string(8) "some 345"
string(11) "some \12345"
string(8) "some 345"
string(11) "some $12345"
<?php
$a = 'some text';
// Either of these will backreference and fail
$b1 = '\12345'; // Should be '\\12345' to avoid backreference
$b2 = '$12345'; // Should be '\$12345' to avoid backreference
$d = array($b1, $b2);
foreach ($d as $b) {
$result1 = preg_replace('#(text)#', $b, $a); // Fails
var_dump($result1);
$result2 = preg_replace('#(text)#', preg_escape_back($b), $a); // Succeeds
var_dump($result2);
}
// Escape backreferences from string for use with regex
function preg_escape_back($string) {
// Replace $ with \$ and \ with \\
$string = preg_replace('#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $string);
return $string;
}
?>