Torrodon Posted January 4, 2011 Share Posted January 4, 2011 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 https://forums.phpfreaks.com/topic/223343-regexp-replace-part-of-pattern-problem/ Share on other sites More sharing options...
sasa Posted January 4, 2011 Share Posted January 4, 2011 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 https://forums.phpfreaks.com/topic/223343-regexp-replace-part-of-pattern-problem/#findComment-1154539 Share on other sites More sharing options...
Torrodon Posted January 4, 2011 Author Share Posted January 4, 2011 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 https://forums.phpfreaks.com/topic/223343-regexp-replace-part-of-pattern-problem/#findComment-1154564 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.