1

假设我有以下链接:

<li class="hook">
      <a href="i_have_underscores">I_have_underscores</a>
</li>

我将如何删除文本中的下划线而不是href?我使用了 str_replace,但这会删除所有下划线,这并不理想。

所以基本上我会留下这个输出:

<li class="hook">
      <a href="i_have_underscores">I have underscores</a>
</li>

任何帮助,非常感谢

4

2 回答 2

6

您可以使用HTML DOM 解析器来获取标签中的文本,然后str_replace()在结果上运行您的函数。


使用我链接的 DOM Parser,它就像这样简单:

$html = str_get_html(
    '<li class="hook"><a href="i_have_underscores">I_have_underscores</a></li>');
$links = $html->find('a');   // You can use any css style selectors here

foreach($links as $l) {
    $l->innertext = str_replace('_', ' ', $l->innertext)
}

echo $html
//<li class="hook"><a href="i_have_underscores">I have underscores</a></li>

就是这样。

于 2010-11-21T18:12:09.167 回答
2

使用DOMDocument而不是正则表达式解析 HTML 更安全。试试这个代码:

<?php

function replaceInAnchors($html)
{
    $dom = new DOMDocument();
    // loadHtml() needs mb_convert_encoding() to work well with UTF-8 encoding
    $dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));

    $xpath = new DOMXPath($dom);

    foreach($xpath->query('//text()[(ancestor::a)]') as $node)
    {
        $replaced = str_ireplace('_', ' ', $node->wholeText);
        $newNode  = $dom->createDocumentFragment();
        $newNode->appendXML($replaced);
        $node->parentNode->replaceChild($newNode, $node);
    }

    // get only the body tag with its contents, then trim the body tag itself to get only the original content
    return mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
}

$html = '<li class="hook">
      <a href="i_have_underscores">I_have_underscores</a>
</li>';
echo replaceInAnchors($html);
于 2010-11-21T19:57:59.110 回答