note 52369 added to function.preg-replace
| From: | TimK dot at osu1 dot php dot net | Date: | Thu, 28 Apr 2005 19:27:26 +0000 |
| Subject: | note 52369 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-88714@lists.php.net to get a copy of this message | ||
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
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52369
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52369&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52369&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52369&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52369&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52369&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52369&report=yes
Search -- http://master.php.net/manage/user-notes.php