我想在php中将<a></a>
替换为[]
,例如,如果我有:
This is sample test to say you <a href="nowhere/333" id="blabah" > help</a> and you can redirect me to <a href="dddd">answer</a>
我希望它被替换为
This is sample test to say you [help] and you can redirect me to [answer]
,
我如何使用正则表达式在 php 中完成这项工作?
使用Document Object Model
并避免使用正则表达式来解析 HTML,不惜一切代价。
echo "[".$dom->getElementsByTagName('a')->item(0)->nodeValue."]";
演示
代码..(对于编辑的问题)
<?php
$html='This is sample test to say you <a href="nowhere/333" id="blabah" > help</a> and you can redirect me to <a href="dddd">answer</a>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$srch=array();$rep=array();
foreach($dom->getElementsByTagName('a') as $atag)
{
$srch[]=trim($atag->nodeValue);
$rep[]="[".trim($atag->nodeValue)."]";
}
echo str_replace($srch,$rep,strip_tags($html));
OUTPUT :
This is sample test to say you [help] and you can redirect me to [answer]
搜索<a.*?>(.*?)<'/a>
并替换为['1]
<?php
$html='<a href="nowhere/333" id="blabah" > help</a>';
echo preg_replace('/<a.*?>(.*?)<'/a>/', '['1]', $html);
答案应该去Shankar Damodaran,这是他扩展的答案,以满足OP的要求:
<?php
$html = 'This is sample test to say you <a href="nowhere/333" ';
$html .= 'id="blabah" > help</a> and you can redirect me to <a ';
$html .= 'href="dddd">answer</a> it replaced to';
$dom = new DOMDocument;
$dom->loadHTML($html);
$elements = count($dom->getElementsByTagName('a'));
for ($i = 0; $i <= $elements; $i++) {
echo "[" . trim($dom->getElementsByTagName('a')->item($i)->nodeValue) . "]";
}
?>
扩展演示