note 106263 modified in function.preg-replace by tularis

From: Date: Sun, 23 Oct 2011 12:47:37 +0000
Subject: note 106263 modified in function.preg-replace by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-184078@lists.php.net to get a copy of this message
[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; } ?> --was-- 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; } ?> http://php.net/manual/en/function.preg-replace.php

« previous php.notes (#184078) next »