iwpg Posted August 14, 2014 Share Posted August 14, 2014 (edited) Hello, I am trying to replace a url and add a sub-id to it, however I'm not quite there. Any help is always appreciated here. In the end, I would like the value of gotoUrl to have the cpId 123abc45 attached to it. I.E. http://example.com/?Aff=56732&SID=123abc45 http://example.com/?Aff=56732&uv=123abc45&product=1834234 http://example.com/?Aff=56732&cid=123abc45&ace=2gs244s3 $gotoUrl = "http://example.com/?Aff=56732&SID="; // OR could be listed as such: // $gotoUrl = "http://example.com/?Aff=56732&uv=default&product=1834234"; // $gotoUrl = "http://example.com/?Aff=56732&cid=&ace=2gs244s3"; // Will attach this to replace value $cpId = "123abc45"; // Possible sid replacements, depending on the url $sidList = array("sid","SID","cid","uv"); if ($gotoUrl){ foreach($sidList as $sidVar){ if (preg_match("/$sidVar/i", $gotoUrl)){ $gotoUrl = preg_replace("#{$sidVar}(?=.*\d)(?=.*[a-z])(?=.*[A-Z])$#", "{$sidVar}={$cpId}", $gotoUrl); } } echo $gotoUrl; } Edited August 14, 2014 by iwpg Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted August 14, 2014 Solution Share Posted August 14, 2014 No regular expressions. Stop it. Regex is for cases when you don't have better tools, and here you do: Use parse_url to break the URL string into components, parse_str to break the query string into key/value pairs, make your modification to the array with a simple assignment, then rebuild the URL using http_build_query to reassemble the query string. Quote Link to comment Share on other sites More sharing options...
iwpg Posted August 14, 2014 Author Share Posted August 14, 2014 Sounds like a plan, will do. My original thinking was that regex would be faster than parse_url based on some past experiences. Thank you! 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.