0

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.

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by matt_platts
0

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;
?>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.