php - Using preg_replace to back reference array key and replace with a value -
i have string this:
http://mysite.com/script.php?fruit=apple
and have associative array this:
$fruitarray["apple"] = "green"; $fruitarray ["banana"] = "yellow";
i trying use preg_replace on string, using key in array reference apple , replace green, 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 isn’t working me; how can manipulate $fruitarray[$1]
in preg_replace statement php recognised, referenced, , replaced green?
thanks!
you need use /e
eval flag, or if can spare 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 whole url concatenation expression enclosed in single quotes. interpreted php expression later, spaces vanish , static url string concatenated whatever in fruitarray.
Comments
Post a Comment