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.

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;
?>

Brilliant! Thanks, much appreciated!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.