4

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!

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent! Your code worked perfectly. Thank you so much, saved me hours of head scratching!
Please do note that the 'e' modifier is depreciated: php.net/manual/en/migration55.deprecated.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.