For Programmers: Free Programming Magazines  


Home > Archive > PHP Language > September 2006 > Re: preg_replace where replacement is an array element to which backreference









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: preg_replace where replacement is an array element to which backreference
Mumia W.

2006-09-14, 6:57 pm

On 09/14/2006 10:03 AM, Dave wrote:
> Hi,
>
> This is an interesting problem I'm faced with. I have been trying all sorts
> of functions to fix it and my last resort is to ask you guys and girls.
>
> I have an array:
> $arr([3]=>"aaa",[104]=>"bbb",[345]=>"ccc",[n]=>"etc");
> $html='<html>....<a href="page.php?var=3">3</a><a
> href="page.php?var=345">345</a> ...<a
> href="page.php?var=n">n</a>...</html>';
>
> I'm trying to get a value from URLs in HTML and use it as a key to output
> the value of $arr.
> i.e. matching the: /page.php?var=(345)/ will output: "ccc";
>
> Here is what I've tried but can't quite get there:
> $html=preg_replace('/(href="page\.php\?)(var=)([0-9]+)/si','\\1var=' .
> eval('\$c='\3'; return \$c;'),$html);
> Outputs the matched var: i.e. 345, but:
>
> $html=preg_replace('/(href="page\.php\?)(var=)([0-9]+)/si','\\1var=' .
> eval('\$c='\3'; return \$arr[\$c];'),$html);
> Won't output anything.
> [...]


Use the /e option to evaluate the replacement string as PHP code:

$arr = Array(3=>"aaa",104=>"bbb",345=>"ccc",'n'=>"etc");
$html='<html>....<a href="page.php?var=3">3</a><a
href="page.php?var=345">345</a> ...<a
href="page.php?var=n">n</a>...</html>';

$html = preg_replace('/(page\.php\?var=)(\w+)/sie',
'"\1".$arr["\2"]',$html);

print $html;

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com