Questions about the Preg_replace () function reverse reference usage.
$Array 1=array (
Array (' ID ' = ' 1 ', ' Name ' = ' Xiao Wang '),
Array (' ID ' = ' 2 ', ' Name ' = ' Xiao Li ')
);
$strA = ' AA Name CC DD ';
$strB = '/\s+ (\w+) \s+/i ';
$Html =preg_replace ($strB, $Array 1[0][' ${2} '], $strA);
Echo $Html;
As shown above, back to reference ${2} It is no problem to write as follows:
$Html =preg_replace ($strB, ' ${2} ', $strA);
However, if I want to use this quoted string as the key name of the array, such as $array[' ${1} ']!. will be an error. How to solve this problem?
notice:undefined index:in F:\Web\wwwroot\CMS\TemplateClass.php on line 236
------to solve the idea----------------------
For php5.5, you can
$Array 1 = Array (
Array (' ID ' = ' 1 ', ' Name ' = ' Xiao Wang '),
Array (' ID ' = ' 2 ', ' Name ' = ' Xiao Li ')
);
$strA = ' AA Name CC DD ';
$strB = '/\s+ (\w+) \s+/ie ';
$Html = Preg_replace ($strB, ' $Array 1[0]["$"] ', $strA);
Echo $Html;
For php5.3 and above, you can
$Array 1 = Array (
Array (' ID ' = ' 1 ', ' Name ' = ' Xiao Wang '),
Array (' ID ' = ' 2 ', ' Name ' = ' Xiao Li ')
);
$strA = ' AA Name CC DD ';
$strB = '/\s+ (\w+) \s+/i ';
$Html = Preg_replace_callback ($strB, function ($m) use ($Array 1) {return $Array 1[0][$m [1]];}, $strA);
Echo $Html;