Jump to content

Preg Match - Cant get it to work.


iwpg

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.