[英]How can I use php preg_replace & the same 'match' twice?
我有以下PHP preg_replace
$src = preg_replace
(
array(
'/(?si)<p\s+class\s*=\s*"Heading1(.*?)"\s*>(.*?)<\/p>/'
),
array(
"<h1>$2<tocentry content='$2' level='0' /></h1>"
),
$src
);
preg_replace使用类Heading1
在HTML文档中搜索任何<p>
,应将其替换为以下内容:
<h1>Introduction<tocentry content='Introduction' level='0' /></h1>
但是,我实际上得到的是:
<h1>Introduction<tocentry content='span class=' level='0' /></h1>
我使用的是相同的匹配参考('2'),但是每个参考都收到不同的结果。 怎么会这样?
非常感谢
编辑
看来问题出在我正在preg_replacing
( $src
)的HTML中。
<p>
的孩子有一个<span>
,这导致了奇怪的结果。
我现在使用以下方法,效果很好:
$src = preg_replace
(
array(
'/(?si)<span\s+class\s*=\s*"Heading1-H(.*?)"\s*>(.*?)<\/span>/'
),
array(
"<h1>$2<tocentry content='$2' level='0' /></h1>"
),
$src
);
$src = <<<EOD
<sometag>Content here content here content here</sometag>
<p class="Heading1stuffstuff">Introduction</p>
<anothertag> More Content. </anothertag>
EOD;
$result = preg_replace (
array(
'/<p\s+class\s*=\s*"Heading1([^"]*)"\s*>([^<]*)<\/p>/si'
),
array(
"<h1>$2<tocentry content='$2' level='0' /></h1>"
),
$src
);
print $result;
/* Outputs:
<sometag>Content here content here content here</sometag>
<h1>Introduction<tocentry content='Introduction' level='0' /></h1>
<anothertag> More Content. </anothertag>
*/
NB语法突出显示是狡猾的,因为SO不喜欢HEREDOC,但是它确实可以工作...老实...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.