Ecco una soluzione sicura UTF-8, che funziona non solo con documenti formattati correttamente, ma anche con frammenti di documenti.
Il mb_convert_encoding è necessario, perché loadHtml() sembra avere un bug con la codifica UTF-8 (vedere here e here).
mb_substr sta tagliando il tag body dall'output, in questo modo si ottiene il contenuto originale senza alcun markup aggiuntivo.
<?php
$html = '<p>Match this text and replace it</p>
<p>Don\'t <a href="/">match this text</a></p>
<p>We still need to match this text and replace itŐŰ</p>
<p>This is <a href="#">a link <span>with <strong>don\'t match this text</strong> content</span></a></p>';
$dom = new DOMDocument();
// loadXml needs properly formatted documents, so it's better to use loadHtml, but it needs a hack to properly handle UTF-8 encoding
$dom->loadHtml(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"));
$xpath = new DOMXPath($dom);
foreach($xpath->query('//text()[not(ancestor::a)]') as $node)
{
$replaced = str_ireplace('match this text', 'MATCH', $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
echo mb_substr($dom->saveXML($xpath->query('//body')->item(0)), 6, -7, "UTF-8");
Riferimenti:
1. find and replace keywords by hyperlinks in an html fragment, via php dom
2. Regex/DOMDocument - match and replace text not in a link
3. php problem with russian language
4. Why Does DOM Change Encoding?
ho letto decine di risposte nel soggetto, quindi mi dispiace se ho dimenticato qualcuno (si prega di commentare e lo farò aggiungi il tuo anche in questo caso).
Grazie per Gordon e fermo per aver commentato my other answer.
fonte
2010-11-17 22:43:03
Usa DOM [come mostrato] (http://stackoverflow.com/questions/4003031/how-to-replace-text-urls-and-exclude-urls-in-html-tags/4037753#4037753) qui e adattare – Gordon
Qual è il tuo comportamento preferito con i tag nidificati all'interno dell'ancora, ad esempio '
Questo è a link with don't match this text content
'? –