iwpg Posted August 14, 2014 Share Posted August 14, 2014 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; } Link to comment https://forums.phpfreaks.com/topic/290444-preg-match-cant-get-it-to-work/ Share on other sites More sharing options...
requinix Posted August 14, 2014 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. Link to comment https://forums.phpfreaks.com/topic/290444-preg-match-cant-get-it-to-work/#findComment-1487751 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! Link to comment https://forums.phpfreaks.com/topic/290444-preg-match-cant-get-it-to-work/#findComment-1487752 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.