当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Using preg_replace_callback and create_function

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: