1

I'm really trying to figure out how to write a preg_replace for this string...

/url/?12345678910&stackoverflow=rocks

...which I want to become...

/url/?_uniqueId_&stackoverflow=rocks

The string contains more ?s and &s, however this is the first occurance of the characters in the string.

I've tried the following, but it doesn't even give me a response:

preg_replace("/\/url\/\?[^)]+\&/","_uniqueId_",$link);

Any help would be greatly appreaciated.

1

1 Answer 1

1

Did you assign the results of preg_replace to a variable?

$link = '/url/?12345678910&stackoverflow=rocks';
$res = preg_replace("/\/url\/\?[^)]+\&/","/url/?_uniqueId_&",$link);
echo $res;

Also, I added the other parts from the replaced string you missed. The regex could otherwise be changed to:

$res = preg_replace("~/url/\?[^&]+&~","/url/?_uniqueId_&",$link);

Which should be a bit faster, and I used different delimiters to avoid excessive escaping. Also & doesn't need to be escaped.

Or use lookarounds:

$res = preg_replace("~(?<=/url/\?)[^&]+(?=&)~","_uniqueId_",$link);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Your first example "kinda" works - it replaces from the first ? to the very last &, which destroys the entire link unfortunately. The other two examples I can't get to work at all. Any ideas about the first one, however?
@MadMarvin Strange... You could change the first one to /\/url\/\?[^)]+?\&/ to make it work better though.
@MadMarvin Oh, I forgot to remove the / from the regex. Both of the 2 last regex should work now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.