kevingarnett2000 Posted May 26, 2007 Share Posted May 26, 2007 Hi, Lets see the following URL: http://somewebsite.com?var1=value1&var2=value2&var3=value3& I need to replace certein parameters in this url so i did something like: $url = "http://somewebsite.com?var1=value1&var2=value2&var3=value3&"; $pattern = "/var1=.*&/"; $replace = "var1=someothervalue&"; echo preg_replace($pattern, $replace, $url); However it is not producing the correct result, it echos: "http://somewebsite.com?var1=someothervalue&" My question is: How do I go about writing the regular expression? Thank you, Kevin Quote Link to comment https://forums.phpfreaks.com/topic/53056-solved-regex-on-url/ Share on other sites More sharing options...
MadTechie Posted May 26, 2007 Share Posted May 26, 2007 what about this <?php $subject= "http://somewebsite.com?var1=value1&var2=value2&var3=value3&"; $Var = "var1"; $Value = "NewValue" $result = preg_replace('/(?:$Var=)(\w+)/im', '$1=$Value', $subject); echo $result; ?> Quote Link to comment https://forums.phpfreaks.com/topic/53056-solved-regex-on-url/#findComment-262120 Share on other sites More sharing options...
effigy Posted May 27, 2007 Share Posted May 27, 2007 The * is greedy, thus gobbling everything up to the last &. You can fix this by making it ungreedy: *?. Alternatively, don't bother matching the variable name only to put it back--use a lookaround: /(?<=var1=)[^&]*/ Quote Link to comment https://forums.phpfreaks.com/topic/53056-solved-regex-on-url/#findComment-262461 Share on other sites More sharing options...
kevingarnett2000 Posted May 27, 2007 Author Share Posted May 27, 2007 That was helpful, thank you very much. Your regards, Kevin Quote Link to comment https://forums.phpfreaks.com/topic/53056-solved-regex-on-url/#findComment-262607 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.