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

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.

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.

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.