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パーサーを使用すると、次のように簡単になります。

$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 に答える