【发布时间】:2017-12-14 02:05:16
【问题描述】:
我正在努力将 html 链接转换为保持相同 html 结构的文本。
我需要隐藏这个 html 页面部分
<div>
<p>text text bla blah</p>
<p><a href="https://google.com" rel="nofollow" target="_blank" title="google">Cool website</a></p>
<p><a href="https://google.com" rel="nofollow" target="_blank" title="google">Cool website</a></p>
</div>
进入这个
<div>
<p>text text bla blah</p>
<p>Cool website https://google.com</p>
<p>Cool website https://google.com</p>
</div>
我找到了一个不错的脚本PHP regex: How to convert HTML string with links into plain text that shows URL after text in brackets 它收集 html 链接并将它们转换为纯文本,这是工作的一部分。
这是我目前所拥有的:
$htmlString = '
<div>
<p>text text bla blah</p>
<p><a href="https://google.com" rel="nofollow" target="_blank" title="google">Cool website</a></p>
<p><a href="https://google.com" rel="nofollow" target="_blank" title="google">Cool website</a></p>
</div>
';
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($htmlString);
$xpath = new DOMXPath($dom);
$links = [];
$linksAsString = '';
foreach ($xpath->query('//a') as $linkElement)
{
$link = [
'href' => $linkElement->getAttribute('href'),
'text' => $linkElement->textContent
];
$links[] = $link;
$linksAsString .= $link['text'] . " {$link['href']}<br/>";
}
libxml_clear_errors();
echo $linksAsString;
当前代码只输出转换后的链接:
Cool website https://google.com
Cool website https://google.com
我将不胜感激。
【问题讨论】:
-
你当前的代码输出什么?你能复制一份样本吗?
-
任何答案都解决了您的问题吗?