简体   繁体   中英

php preg_replace regex with ? and &

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM