Jump to content

[SOLVED] using preg_replace() with other functions


dsaba

Recommended Posts

ah yes I just figured this out..

but you have to do more, here it is completely:

<?php$str = 'hello and hi hello and hi';
$pat = '~(hello )(and)( hi)~e';
$str = preg_replace($pat, "'\\1'.strtoupper('\\2').'\\3'", $str);
echo $str;
?>

 

do you HAVE to use the e modifier and use the two slashes \\ ?

ok now something weird...

I tried this:

<?php
$str = '" \\an//d " " \\an//d "';
$pat = '~(" )(\\\an//d)( ")~e';
$str = preg_replace($pat, "'change1_$1'.urldecode('$2').'$3_change3'", $str);
echo $str;
?>

 

and it outputs:

change1_\" \an//d \"_change3 change1_\" \an//d \"_change3

 

when it should output:

change1_" \an//d "_change3 change1_" \an//d "_change3

 

its adding an extra slash on the quotes, why is it doing this?

1. adding slashes to the $str in the begg. will change the entire haystack

2. stripping slashes from the $str after preg_replace will strip too many slashes

 

The only way to "do it" is by changing the line to this:

$str = preg_replace($pat, "'change1_'.stripslashes('$1').urldecode('$2').stripslashes('$3').'_change3'", $str);

 

but this isn't getting at the root of the problem if you know what I mean..

can anyone tell me what's going on here?

Per the docs:

 

e (PREG_REPLACE_EVAL)

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes and NULL chars will be escaped by backslashes in substituted backreferences.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.