Str_replace与正则表达式

时间:2010-11-21 18:08:39

标签: php regex str-replace

说我有以下链接:

<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>

任何帮助,非常感谢

2 个答案:

答案 0 :(得分:6)

您可以使用HTML DOM parser获取代码中的文字,然后在结果上运行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>

就是这样。

答案 1 :(得分: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);