0
我正在寻找一种方式来改造这个:更换HTML标记的HREF
...<a href="showinfo:3875//[integer]">[inner content]</a>...
进入这个:
...<a href="http://somelink.com/[inner content]">[inner content]</a>...
的情况下有多个链接与其他showinfo:整数]值。 (我可以处理这些的)
感谢您的帮助, 巴林特
编辑:多亏了凯撒的答案,这里是工作的代码片段:
$html = $a;
$dom = new \DOMDocument;
@$dom->loadHTML($html); //Cannot guarantee all-valid input
foreach ($dom->getElementsByTagName('a') as $tag) {
// Fixed strstr order and added a != false check - the, because the string started with the substring
if ($tag->hasAttribute('href') && strstr($tag->getAttribute('href'), 'showinfo:3875') != false) {
$tag->setAttribute('href', "http://somelink.com/{$tag->textContent}");
// Assign the Converted HTML, prevents failing when saving
$html = $tag;
}
}
return $dom->saveHTML($dom);
}
谢谢 - 效果很好! – molbal
编辑:在问题中添加最终解决方案 – molbal
@molbal关于您编辑的问题的一些注释:您可能想使用'stristr()'(请参阅编辑答案)。你也不需要检查'!= false'。忽略它是一样的。但是,如果你这样做,至少用'!=='做一个类型安全检查。如果你**得到警告**,那么请按照[这个答案](http://stackoverflow.com/questions/1148928/disable-warnings-when-loading-non-well-formed-html-by-domdocument-php/17559716#17559716)查看如何禁止警告。或者只是_fix_你的HTML,如果你在控制它:) – kaiser