开发者

Using preg_replace to back reference array key and replace with a value

I have a string like this:

http://mysite.com/script.php?fruit=apple

And I have an associative array like this:

$fruitArray["apple"] = "green";
$fruitArray ["banana"] = "yellow";

I am trying to use preg_replace on开发者_JAVA技巧 the string, using the key in the array to back reference apple and replace it with green, like this:

$string = preg_replace('|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|', 'http://mysite.com/'.$fruitArray[$1].'/', $string);

The process should return

http://mysite.com/green/

Obviously this isn’t working for me; how can I manipulate $fruitArray[$1] in the preg_replace statement so that the PHP is recognised, back referenced, and replaced with green?

Thanks!


You need to use the /e eval flag, or if you can spare a few lines preg_replace_callback.

  $string = preg_replace(
     '|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
     ' "http://mysite.com/" . $fruitArray["$1"] ',
     $string
  );

Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜