note 106263 added to function.preg-replace

From: Date: Sun, 23 Oct 2011 06:47:14 +0000
Subject: note 106263 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-184070@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 14.201.79.146 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/106263 Del: integrated -- https://master.php.net/note/delete/106263/integrated Del: useless -- https://master.php.net/note/delete/106263/useless Del: bad code -- https://master.php.net/note/delete/106263/bad+code Del: spam -- https://master.php.net/note/delete/106263/spam Del: non-english -- https://master.php.net/note/delete/106263/non-english Del: in docs -- https://master.php.net/note/delete/106263/in+docs Del: other reasons-- https://master.php.net/note/delete/106263 Reject -- https://master.php.net/note/reject/106263 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#184070) next »