且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 preg_replace 支持引用数组键并替换为值

更新时间:2023-12-05 13:16:34

您需要使用 /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.