使用 preg_replace 支持引用数组键并替换为值 [英] Using preg_replace to back reference array key and replace with a value

查看:29
本文介绍了使用 preg_replace 支持引用数组键并替换为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

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";

我正在尝试在字符串上使用 preg_replace,使用数组中的键来支持引用苹果并将其替换为绿色,如下所示:

I am trying to use preg_replace on 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);

进程应该返回

http://mysite.com/green/

显然这对我不起作用;如何在 preg_replace 语句中操作 $fruitArray[$1] 以便 PHP 被识别、反向引用并替换为绿色?

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?

谢谢!

推荐答案

您需要使用 /e eval 标志,或者如果您可以节省几行 preg_replace_callback.

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
  );

注意整个 URL 连接表达式是如何用单引号括起来的.稍后它将被解释为 PHP 表达式,空格将消失,静态 URL 字符串将与 FruitArray 中的任何内容连接.

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.

这篇关于使用 preg_replace 支持引用数组键并替换为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆