关于preg_replace()函数反向引用用法的有关问题

WBOY
Release: 2016-06-13 12:26:30
Original
1257 people have browsed it

关于preg_replace()函数反向引用用法的问题。

<br />$Array1=array(<br />	array('ID'=>'1','Name'=>'小王'),<br />	array('ID'=>'2','Name'=>'小李')<br />	);<br /><br />$strA='AA Name CC DD';<br />$strB='/\s+(\w+)\s+/i';<br />$Html=preg_replace($strB, $Array1[0][‘${2}’], $strA);<br />echo $Html;<br />
Copy after login


如上面所示返向引用${2}如下这么写是没问题的:
$Html=preg_replace($strB, ‘${2}’, $strA);
Copy after login


但是,如果我想把这个引用过来的字符串当作数组的键名,如$array['${1}']!。就会报错。如何解决这个问题呢?
Notice: Undefined index: in F:\Web\wwwroot\CMS\TemplateClass.php on line 236
------解决思路----------------------
对于 php5.5 一下,可以
$Array1 = array(<br />    array('ID'=>'1','Name'=>'小王'),<br />    array('ID'=>'2','Name'=>'小李')<br />    );<br /> <br />$strA = 'AA Name CC DD';<br />$strB = '/\s+(\w+)\s+/ie';<br />$Html = preg_replace($strB, '$Array1[0]["$1"]', $strA);<br />echo $Html;<br />
Copy after login

对于 php5.3及以上,可以
$Array1 = array(<br />    array('ID'=>'1','Name'=>'小王'),<br />    array('ID'=>'2','Name'=>'小李')<br />    );<br /> <br />$strA = 'AA Name CC DD';<br />$strB = '/\s+(\w+)\s+/i';<br />$Html = preg_replace_callback($strB, function($m) use ($Array1) { return $Array1[0][$m[1]];}, $strA);<br />echo $Html;
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!