About the reverse reference usage of the preg_replace () function. $ Array1array (array (ID & gt; 1, Name & gt; Xiao Wang), array (ID & gt; 2, Name & gt; Xiao Li); $ strAAA & nbsp; name & nbsp; CC & nbsp; DD; $ strBs + (w +) s + I; reverse reference usage of the preg_replace () function.
$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);
$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/I ';
$ Html = preg_replace ($ strB, $ Array1 [0] ['$ {2}'], $ strA );
Echo $ Html;
As shown above, returning to reference $ {2} is okay as follows:
$Html=preg_replace($strB, ‘${2}’, $strA);
However, if I want to use the referenced string as the key name of the array, for example, $ array ['$ {1}']. An error is reported. How can this problem be solved?
Notice: Undefined index: in F: \ Web \ wwwroot \ CMS \ TemplateClass. php on line 236
------ Solution ----------------------
For php5.5, you can
$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);
$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/ie ';
$ Html = preg_replace ($ strB, '$ Array1 [0] ["$1"]', $ strA );
Echo $ Html;
For php5.3 and above, you can
$ Array1 = array (
Array ('id' => '1', 'name' => 'Wang '),
Array ('id' => '2', 'name' => 'Lily ')
);
$ StrA = 'AA Name CC DD ';
$ StrB = '/\ s + (\ w +) \ s +/I ';
$ Html = preg_replace_callback ($ strB, function ($ m) use ($ Array1) {return $ Array1 [0] [$ m [1] ;}, $ strA );
Echo $ Html;