1

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 ?

2
  • shouldn't it be $items->{$1} ? Commented Dec 27, 2016 at 16:08
  • You can try with echo preg_replace('/\%(.*?)\%/e', $items->${1}, $content); Commented Dec 27, 2016 at 16:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help. Please mark this as the solution to your question if this solved your problem. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.