Str_replace с регулярным выражением - PullRequest
1 голос
/ 21 ноября 2010

Скажите, что у меня есть следующая ссылка:

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

6 голосов
/ 21 ноября 2010

Вы можете использовать HTML DOM-парсер , чтобы получить текст внутри тегов, а затем запустить функцию str_replace() для результата.


Использование DOM Parser Iсвязаны, это так просто, как-то так:

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

Вот и все.

2 голосов
/ 21 ноября 2010

Безопаснее анализировать HTML с DOMDocument вместо регулярных выражений. Попробуйте этот код:

<?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);
...