Martin
Martin

Reputation: 2017

preg_replace() changes are not being preserved while looping

I want to replace word groups by links. I use a multi-dimensional array to define these (in the real world there will be thousands of them). Here's the code: <?php

$text = "<html><body><pre>
Here is Foo in text.
Now come Baz? and Bar-X.
Replace nothing here: Foo (followed by brackets).
</pre></body></html>";

$s = array(
  array("t" => "Foo", "u" => "http://www.example.com", "c" => "foo"),
  array("t" => "Baz?", "u" => "http://www.example.net", "c" => "test"),
  array("t" => "Bar-X", "u" => "http://www.example.org", "c" => "test")
 );

foreach ($s as $i => $row) {
  $replaced = preg_replace('/(?=\Q'.$row["t"].'\E[^(]+$)\b\Q'.$row["t"].'\E\b/m',
                           '<a href="'.$row["u"].'" class="'.$row["c"].'">'.$row["t"].'</a>',
                           $text);
 }
echo $replaced;

?>

The problem is that only one array element is replaced and not all. It's something about $text in preg_replace().

Upvotes: 0

Views: 89

Answers (1)

WesleyE
WesleyE

Reputation: 1384

You have to add to the $replaced var, now you are overwriting the variable.

    <?php

    $text = "<html><body><pre>
    Here is Foo in text.
    Now come Baz? and Bar-X.
    Replace nothing here: Foo (followed by brackets).
    </pre></body></html>";

    $s = array(
      array("t" => "Foo", "u" => "http://www.foo.com", "c" => "foo"),
      array("t" => "Baz?", "u" => "http://www.baz.net", "c" => "test"),
      array("t" => "Bar-X", "u" => "http://www.baz.org", "c" => "test")
     );

    $replaced = $text;
    foreach ($s as $i => $row) {
      $replaced = preg_replace('/(?=\Q'.$row["t"].'\E[^(]+$)\b\Q'.$row["t"].'\E\b/m',
                               '<a href="'.$row["u"].'" class="'.$row["c"].'">'.$row["t"].'</a>',
                               $replaced );
     }
    echo $replaced;

    ?>

Upvotes: 1

Related Questions