user3125921
user3125921

Reputation: 23

PHP preg_replace in foreach loop

I am trying to use preg_replace in a foreach loop.

I need to replace all keywords wrapped between '%' and use the back reference.

For example, in my text I have few keywords like %author% %title% I need to replace the keywords so they look like $items->author and $items->title

I have tried with the following code but it just displays $items->author as a text and not retrieving the info from the array.

      foreach ($xml->book as $items) {
           echo preg_replace('/\%(.*?)\%/e', '$items->${1}', $content);
      }

Any idea for this ?

Upvotes: 1

Views: 1851

Answers (1)

Jerodev
Jerodev

Reputation: 33196

You will have to use preg_replace_callback for this. You cannot just put code as the second parameter in the preg_replace function.

Like this:

<?php

    foreach ($xml->book as $items) {
        echo preg_replace_callback('/\%(.*?)\%/e', function ($matches) use ($items) {
            return $items->{$matches[1]};
        }, $content);
    }

Also, it would be best to check if a match was found and if the $items array contains a key with this name.

Upvotes: 1

Related Questions