Jump to content

regexp replace part of pattern problem


Torrodon

Recommended Posts

I'm trying to replace a color in css file using preg_replace. First i have tried to replace part of pattern using $1 and $3, but it didn't work. Next i have extracted the pattern into $matches array, replaced one of them and combined them as new replace string. It worked as expected. I think there is difference how parts of pattern defined by () are matched by preg_match->$matches_array and preg_replace->$1,$2,$3...

 

I know my explanation of the problem is not good at all so i'm attaching very simple php file (zipped) that show the error.

 

Can someone help me understand what i'm doing wrong?

 

[attachment deleted by admin]

Link to comment
Share on other sites

try

$pattern = '@(body[^\{\}]*?\{[^\{\}]*?background:)#([0-9A-F]{6})(;[^\{\}]*?\})@s';
echo $new_str_1 = preg_replace($pattern,"$1#".$newcolor."$3",$str);

in your example replace string is "$11A2B3C$3"

start of it $11 means 11th subpatern that not exist

i remove # from 1st subpatern and add it literaly

Link to comment
Share on other sites

Thank you, @sasa

Now after you mentioned it i found this exception in the documentation. (http://php.net/manual/en/function.preg-replace.php)

I've also found my second mistake - the solution does not work with double quotes. So finally this is working:

$new_str_1 = preg_replace($pattern,'${1}'.$newcolor.'$3',$str);

Too bad this is unlikely to help anyone else due to my poor description.

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.