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

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -