Using preg_replace to back reference array key and

2019-06-24 07:31发布

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 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!

标签: php regex url
1条回答
唯我独甜
2楼-- · 2019-06-24 07:47

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.

查看更多
登录 后发表回答