0

I am trying to replace the words in a sentence using preg_replace_callback.

"%1% and %2% went up the %3%"

should become

"Jack and Jill went up the hill"

I have given my code below.

<?php
  $values = array("Jack", "Jill", "hill");
  $line = "%1% and %2% went up the %3%";
  $line = preg_replace_callback(
    '/%(.*?)%/',
    create_function(
        // single quotes are essential here,
        // or alternative escape all $ as \$
        '$matches',
        'return $values[$matches[1]-1];'
    ),
    $line
  );
  echo $line;
?>

What I am getting is

" and went up the "

If I give return $matches[1]-1; , I am getting

"0 and 1 went up the 2"

Is it a scope issue ? How to make this working ? Any help would be appreciated.

1 Answer 1

2

It is indeed a scoping issue - your anonymous function created by create_function does not have access to $values.

This should work (>= PHP 5.3.0)

<?php
  $values = array("Jack", "Jill", "hill");
  $line = "%1% and %2% went up the %3%";
  // Define our callback here and import $values into its scope ...
  $callback = 
    function ($matches) use ($values)
    {
      return $values[$matches[1]-1];
    };

  $line = preg_replace_callback(
    '/%(.*?)%/',
    $callback, // Use it here.
    $line
  );
  echo $line;
?>

By declaring the callback function with use ($values), $values will be imported into its scope and available when it's called. This is the concept of a 'closure' over $values if you'd like to Google it further :).

Hope this helps.

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

Comments

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.