Jump to content

Preg Match - Cant get it to work.


iwpg
Go to solution Solved by requinix,

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;
        }
Edited by iwpg
Link to comment
Share on other sites

  • Solution

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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