【问题标题】:Converting HTML to show link URLs using PHP使用 PHP 将 HTML 转换为显示链接 URL
【发布时间】: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


【解决方案1】:

首先,您的 HTML 格式不正确,因为需要将 &amp;amp; 编码为其 HTML 实体 &amp;amp;。解决这个问题给了我们:

$html = '<div>
 <p>Some text &amp; a <a href="http://abc.com/index.php?x=123&amp;y=abc">link</a>. Done</p>
 <p>More text &amp; a <a href="http://abc.com/index.php?x=123&amp;y=abc">link</a>. Done</p>
</div>';

从这里开始,您不应该使用正则表达式。它非常脆弱,不适合解析 HTML。相反,您可以使用 PHP 的 DOMDocument 类来解析 HTML,提取 &lt;a&gt; 标记,从中提取您想要的信息,创建新的 HTML 元素,并将它们插入到适当的位置。

$doc = new DOMDocument;
$doc->loadHTML( $html);

$xpath = new DOMXPath($doc);
foreach( $xpath->query( '//a') as $a) {
    $strong = $doc->createElement( 'strong', $a->textContent);
    $i = $doc->createElement( 'i', htmlentities( $a->getAttribute('href')));
    $a->parentNode->insertBefore( $strong, $a);
    $a->parentNode->insertBefore( $i, $a);
    $a->parentNode->removeChild( $a);
}

这个prints

<p>Some text &amp; a <strong>link</strong><i>http://abc.com/index.php?x=123&amp;y=abc</i>. Done</p> 
<p>More text &amp; a <strong>link</strong><i>http://abc.com/index.php?x=123&amp;y=abc</i>. Done</p>

【讨论】:

  • 谢谢尼克。我会详细讨论这个。
  • DOMXPath()。以前从未使用过。无论如何,您的解决方案都很完美。我一定会研究它,所以我知道它为什么有效..
【解决方案2】:

您需要使用正则表达式。

$newHtml = preg_replace(/<a[\s\w"'=\t\n]*href="(.*?)"[\s\w"'=\t\n]*>(.*?)<\/a>/i, "<strong>${2}</strong> <i>${1}</i>", $html);

你可以看到正则表达式here

【讨论】:

  • 那个正则表达式只适用于那个非常具体的文本块。 OP 需要使用通用的 DOM 解析器。
  • 谢谢戈苏。我会试一试,但也会探索安迪的建议。
  • 正则表达式在这种情况下有效,它将替换任何 HTML 的所有链接,它不会解析 html,它不会查看其格式是否错误,但它可以工作,markdown 以这种方式工作。
猜你喜欢
  • 2011-01-30
  • 2015-04-22
  • 1970-01-01
  • 2010-12-29
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多