note 17799 added to function.preg-replace

From: Date: Tue, 25 Dec 2001 19:42:41 +0000
Subject: note 17799 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-23832@lists.php.net to get a copy of this message
preg_replace appears to do some parameter quoting, but it is not quite well documented. There seem to be some design flaws. It replaces all \ with \\, ' with \' and all " with \". This makes it is difficult to get the strings unmodified to the matcher functions when using /e. Here's some example code: . | <?php | | # This string contains some difficult characters. | $s = "begin \\keno, 'text', \"text2\", \$cash.end"; | | function handle($s) | { | echo "Got: $s\n"; | } | print "Original: $s\n"; | preg_replace('/^(.*)$/e', 'handle("\1")', $s); | preg_replace('/^(.*)$/e', 'handle("$1")', $s); | preg_replace('/^(.*)$/e', "handle('\\1')", $s); | preg_replace('/^(.*)$/e', "handle('\$1')", $s); | preg_replace('/^(.*)$/e', "print $1", $s); ' Output: . | Original: begin \keno, 'text', "text2", $cash.end | Got: begin \keno, \'text\', "text2", .end | Got: begin \keno, \'text\', "text2", .end | Got: begin \keno, 'text', \"text2\", $cash.end | Got: begin \keno, 'text', \"text2\", $cash.end | <b>Fatal error</b>: Failed evaluating code: | print begin \\keno, \'text\', \"text2\", $cash.end ' Thus, to get all characters correctly, the replacefunction must be specified as "func('\$1')", and the function must do str_replace('\"', '"', $input), or it won't get the characters correctly. This is inconvenient.   Also it is quite harmful that preg_replace rejects all escape characters (0..31) in the input string. This makes it difficult to make functions that replace escape codes (for example mirc colours, which start with the ^C character (#3)) with html codes.   Replacing control characters in input with some other recognizable characters makes it impossible to distinguish those deputy characters from the "real" that kind of characters. (Meaning that if you replace ^C with ÿ before doing preg_replace, you can't know if the matched character was originally ^C or ÿ.) Let's hope we get a patch fixing this soon, allowing any <32 characters to be used in the input. Currently this just looks like shooting the leg. -- http://www.php.net/manual/en/function.preg-replace.php http://master.php.net/manage/user-notes.php?action=edit+17799 http://master.php.net/manage/user-notes.php?action=delete+17799 http://master.php.net/manage/user-notes.php?action=reject+17799

« previous php.notes (#23832) next »