【问题标题】:Str_replace with regex用正则表达式替换 Str_replace
【发布时间】:2011-05-13 11:14:47
【问题描述】:

假设我有以下链接:

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

任何帮助,非常感谢

【问题讨论】:

标签: php regex str-replace


【解决方案1】:

您可以使用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>

就是这样。

【讨论】:

  • 谢谢,我应该查看网站的哪个部分?
  • 在首页,您需要查看“下载和文档”下的两个链接
  • 它比 Stillstanding 的解决方案慢得多(30 毫秒对 1 毫秒),这对我来说似乎是最好的方法(但使用 "//text()[(ancestor::a)]" xPath 查询)。
【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2021-09-20
    • 2021-03-21
    • 2020-11-05
    • 2014-03-29
    相关资源
    最近更新 更多