将所有<a>标签替换为php中的某个字符

Yus*_*sef 0 php regex dom function output

我想替换<a></a>[]php,例如,如果我有:

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中完成这项工作?

Sha*_*ran 7

使用a Document Object Model并避免使用正则表达式来不惜一切代价解析HTML.

echo "[".$dom->getElementsByTagName('a')->item(0)->nodeValue."]";
Run Code Online (Sandbox Code Playgroud)

Demo

代码..(针对编辑过的问题)

<?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));
Run Code Online (Sandbox Code Playgroud)

OUTPUT :

This is sample test to say you   [help] and  you can redirect me to [answer]
Run Code Online (Sandbox Code Playgroud)