note 52369 deleted from function.preg-replace by tularis

From: Date: Sun, 18 Jun 2006 13:27:00 +0000
Subject: note 52369 deleted from function.preg-replace by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-114313@lists.php.net to get a copy of this message
Note Submitter: Tim K. ---- if you use preg_replace with the \e modifier and pass some captured text to a function you will notice the following behaviour: if you pass the replacement parameter (\1) in double quotes, all single quotes in the string are getting escaped, if you pass the parameter in single quotes, all double quotes are getting escaped. as an example look at the following code: function showText($info, $in) { echo $info.': '.$in."\n"; } $pattern = '/#(.*)#/e'; $subject = '#\'quote\' - "double quote" - \\backslash\\#'; preg_replace($pattern, 'showText(\'test1.1\', \'\1\')', $subject); preg_replace($pattern, 'showText(\'test1.2\', "\1")', $subject); preg_replace($pattern, "showText('test1.3', '\\1')", $subject); preg_replace($pattern, "showText('test1.4', \"\\1\")", $subject); // output: // test1.1: 'quote' - \"double quote\" - \backslash\ // test1.2: \'quote\' - "double quote" - \backslash\ // test1.3: 'quote' - \"double quote\" - \backslash\ // test1.4: \'quote\' - "double quote" - \backslash\ consequences: you might have to take care about the extra escaped single or double quotes in the function you are calling. Unfortunatly this depends on the way you add the capture text into the function call - so there is no way of knowing within the function what to strip away... another thing in case it helps someone: you can use variables within the function call and if you are using them they are local to the calling preg_replace. as an example: $a = 'variable $a in global name space'; function local_function() { $a = 'variable $a in local_function'; preg_replace('/#(.*)#/e', 'showText(\'test2.1\', $a)', '#test#'); } local_function(); preg_replace('/#(.*)#/e', 'showText(\'test2.2\', $a)', '#test#'); // output: // test2.1: variable $a in local_function // test2.2: variable $a in global name space

« previous php.notes (#114313) next »