954,597 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

PHP backreference referencing a hash key

Im trying to use a regular expression backreference to reference a hash key.

Here's an example of the non working code so you can see what I'm trying to achieve (I hope!):

$str="String of text containing item1 and item2";
$x['item1']="Item 1";
$x['item2']="Item 2";
$str=preg_replace("/item1/","$x[\${1}1]",$str);
print $str;


I want to get the result "String of text containing Item 1 and Item 2" - it must use the backreference to get the result out of the hash. Anyone got any ideas?

Thanks in advance,
Matt.

matt_platts
Newbie Poster
11 posts since Jan 2011
Reputation Points: 10
Solved Threads: 3
 

You need to enclose the expression in parenthesis for the back reference to work. Since you need to replace based on your php array, you also need to use the 'e' switch at the end of the regex:

<?php
$str="String of text containing item1 and item2";
$x['item1']="Item 1";
$x['item2']="Item 2";
$str=preg_replace('/(item\d+)/e','$x[$1]',$str);
print $str;
?>
hielo
Veteran Poster
1,124 posts since Dec 2007
Reputation Points: 116
Solved Threads: 244
 

Brilliant! Thanks, much appreciated!

matt_platts
Newbie Poster
11 posts since Jan 2011
Reputation Points: 10
Solved Threads: 3
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: