Nedim Nedim - 5 months ago 16
PHP Question

preg_replace itereation

This is how my code looks like:

$x = '<p>This is a <a href="1.php?src=123">first</a> paragraph.</p>
<p>This is a <a href="2.php?id=987">second</a> pararaph.</p>
<p>This is a <a href="3.php?reL=666">third</a> paragraph'</p>;


I would like to replace all these links and add a number. A number of iteration. In the first link, it should add
&i=1
, in second
&i=2
, third
&i=3
, fourth
&i=4
, etc.

Edit: I've tried to match all
a
tags and get them to the array:

$input = '<p><a href="1.php?src=123">x</a></p> <p><a href="2.php?id=987">y</a></p> <p><a href="3.php?rel=666">third</a></p>';
$output = [];
preg_match("/href=\"(.*)\"/", $input, $output);
print_r($output);


However, it returns an array with two elements, and at phpliveregex.com it's a bit different.

Answer

You were nearly there.

$input = '<p><a href="1.php?src=123">x</a></p> <p><a href="2.php?id=987">y</a></p> <p><a href="3.php?rel=666">third</a></p>';
$output = [];
preg_match_all("/href=\"(.*?)\"/", $input, $output);
print_r($output);

There were two problems:

  • preg_match only matches the first occurrence; use preg_match_all instead
  • make your regex lazy by adding a question mark: (.*?) - it should match as short a string as possible (i.e. stop at the first " it finds instead of the last)
Comments