$Array 1=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
Reply to discussion (solution)
For php5.5, you can
$Array 1 = 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 ( ' 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;