Jump to content

[SOLVED] using preg_replace() with other functions


dsaba

Recommended Posts

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

 

I want it to echo:

hello AND hi hello AND hi

 

however it echoes:

hello and hi hello and hi

 

 

how can I fix it?

Link to comment
Share on other sites

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 \\ ?

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.