the*_*art 7 php anchor href domdocument createtextnode
我有一个函数,使用Php的DOMDocument替换字符串中的锚点'href属性.这是一个片段:
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML($text);
$anchors = $doc->getElementsByTagName('a');
foreach($anchors as $a) {
$a->setAttribute('href', 'http://google.com');
}
return $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)
问题是loadHTML($ text)围绕doctype,html,body等标签中的$ text.我尝试通过这样做而不是loadHTML()来解决这个问题:
$doc = new DOMDocument('1.0', 'UTF-8');
$node = $doc->createTextNode($text);
$doc->appendChild($node);
...
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会编码所有实体(包括锚点).有谁知道如何关闭它?我已经彻底查看了文档,并试图破解它,但无法弄明白.
谢谢!:)
$text 是带有占位符锚标记的翻译字符串
如果这些占位符具有严格的、定义良好的格式,则简单的preg_replace或preg_replace_callback可能会起作用。
一般来说,我不建议使用正则表达式来处理 html 文档,但对于一个定义明确的小子集来说,它们是合适的。