@dillix

Как заменить словосочетание везде, кроме тегов h1-h6 и a?

Есть html код, необходимо с помощью регулярных выражений заменить одно словосочетание на другое везде, кроме тегов h1-h6 и ссылок. Я делал с помощью pregmatch, а потом implode. Подскажите как оптимально решить задачу?
  • Вопрос задан
  • 2537 просмотров
Пригласить эксперта
Ответы на вопрос 3
m5web
@m5web
Python, js
html код где находится(в базе, в шаблоне)?
при каких условиях должна происходить замена текста?

пальцем в небо php.net/manual/ru/function.str-replace.php#refsect...

Если я верно понял задачу, то:
$text = 'Man Gnoy artrit in the text
Some text about artrit.
There are many types of side. Gnoy artrit may be other side.
Non gnoy artrit
Anoter text gnoy artrit side.
Some ending text.
Non gnoy artrit
Anoter text of gnoy artrit side.
Some ending text.';

$search = 'gnoy artrit';

$sWords = explode(' ',$search);
$replaceWords = array();

foreach ($sWords as $key=>$val) {
    $replaceWords[$key]='<strong>' . $val . '</strong>';
}

$text = str_ireplace($sWords, $replaceWords, $text);

print_r($text);
Ответ написан
@SilverSlice
$html = '<h1>Man Gnoy artrit in the text</h1>
Some text about artrit.
<p>There are many types of side. Gnoy artrit may be other side and gnoy artrit once more.</p>
Non gnoy artrit
<a href="#">Anoter text gnoy artrit side.</a>
Some ending text.
Non gnoy artrit
<h5>Anoter text of gnoy artrit side.</h5>
Some ending text.';

$dom = new DomDocument();
$dom->loadHTML($html);

$keyword = 'gnoy artrit';
$xpath = new DomXPath($dom);
$nodes = $xpath->query("
    //text()[contains(
        translate(., 'ABCDEFGHJIKLMNOPQRSTUVWXYZ', 'abcdefghjiklmnopqrstuvwxyz'),
        '$keyword')
        and not(ancestor::h1)
        and not(ancestor::h2)
        and not(ancestor::h3)
        and not(ancestor::h4)
        and not(ancestor::h5)
        and not(ancestor::h6)
        and not(ancestor::a)]
");
foreach ($nodes as $node) {
    $replace = function($node, $keyword) use (&$replace) {
        $startPos = stripos($node->textContent, $keyword);
        if ($startPos === false) {
            return;
        }

        $keynode = $node->splitText($startPos);
        $restnode = $keynode->splitText(strlen($keyword));
        $replacement = new DOMElement('strong', $keynode->textContent);
        $node->parentNode->replaceChild($replacement, $keynode);
        $replace($restnode, $keyword);
    };
    $replace($node, $keyword);
}

echo $html;
echo '<hr>';
echo $dom->saveHTML();
Ответ написан
@ShamblerR
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы