【发布时间】:2012-11-17 20:50:40
【问题描述】:
是否可以使用 PHP 将第一个文本块转换为第二个文本块?如果是这样,怎么做?谢谢
<div>
<p>Some text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
<p>More text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
</div>
<div>
<p>Some text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
<p>More text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
</div>
编辑。根据安迪的建议,查看类似以下内容。仍在为链接转换而苦苦挣扎,但它看起来是一个好的开始。
libxml_use_internal_errors(true); //Temporarily disable errors resulting from improperly formed HTML
$doc = new DOMDocument();
$doc->loadHTML($array['message_text']);
$a = $doc->getElementsByTagName('a');
foreach ($a as $link)
{
//Where do I go from here?
}
$array['message_text'] = $doc->saveHTML();
libxml_use_internal_errors(false);
【问题讨论】:
-
请查看使用适当的 DOM 解析器。除了处理非常狭窄的测试用例外,正则表达式不是一个好的解决方案。见php.net/manual/en/book.dom.php
-
谢谢安迪。我的想法类似于我在编辑后的帖子中的内容。
标签: php regex html-parsing