dsaba Posted December 27, 2007 Share Posted December 27, 2007 <?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? Quote Link to comment Share on other sites More sharing options...
rajivgonsalves Posted December 27, 2007 Share Posted December 27, 2007 your expression should be $pat = '~(hello )(and)( hi)~e'; use the 'e' modifyer Quote Link to comment Share on other sites More sharing options...
dsaba Posted December 27, 2007 Author Share Posted December 27, 2007 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 \\ ? Quote Link to comment Share on other sites More sharing options...
dsaba Posted December 27, 2007 Author Share Posted December 27, 2007 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? Quote Link to comment Share on other sites More sharing options...
dsaba Posted December 29, 2007 Author Share Posted December 29, 2007 bump Quote Link to comment Share on other sites More sharing options...
effigy Posted January 2, 2008 Share Posted January 2, 2008 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.