Jump to content

[SOLVED] Preg_replace() Is Only Replacing The First Match


ShadowMetis

Recommended Posts

For some reason my preg_replace() is only replacing the first matched $pattern in the $subject. Before this the $pattern and $replacement were arrays and the second half worked flawlessly to replace all the matches, however I separated it out to try to isolate the problem. No luck though. Any advice would be greatly appreciated.

 

This is the snippet of $subject that is the target of this replacement.

<a href="/w/index.php?title=Special:Search&search=blaz&fulltext=Search&offset=20&limit=20">2</a> <a href="/w/index.php?title=Special:Search&search=blaz&fulltext=Search&offset=40&limit=20">3</a> <a href="/w/index.php?title=Special:Search&search=blaz&fulltext=Search&offset=60&limit=20">4</a> <a href="/w/index.php?title=Special:Search&search=blaz&fulltext=Search&offset=80&limit=20">5</a> <a href="/w/index.php?title=Special:Search&search=blaz&fulltext=Search&offset=20&limit=20"><span style='font-size: small'>Next</span> »</a>

 

This is the pattern, replacement, and preg_replace() code.

$pattern = "/<a href=\"\/w\/index\.php\?title=Special:Search&search=(.+)&fulltext=Search&offset=(\d+)&limit=(\d+)\">(.+)<\/a>/";
$replace = '<a href="' . $_SERVER['PHP_SELF'] . '?submit=true&fulltext=Search&search=${1}&offset=${2}&limit=${3}">${4}</a>';
$result = preg_replace($pattern, $replace, $result);

Link to comment
Share on other sites

Ok it's obvious to me at this point that my problem lies with the pattern. I've tried a few different things with adverse results. I don't have all that much experience with PCRE so if anyone can help me figure out the best pattern to use I'd love you for a few minutes and be grateful for even longer. Thanks in advance.

Link to comment
Share on other sites

After many attempts I went back to my original pattern and added the U(ungreedy) internal option (ie. /pattern/U) as I originally assumed was my problem but for some stupid reason never bothered to try. Thanks anyway.

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.