Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created December 1, 2017 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpfiddle/c50bf8ddce770d9e93101fae4c54c973 to your computer and use it in GitHub Desktop.
Save phpfiddle/c50bf8ddce770d9e93101fae4c54c973 to your computer and use it in GitHub Desktop.
[ Posted by Sil3ntOne ] bulk word replace for html content
<?php
function treatNode($node)
{
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $child){
treatNode($child);
}
} else {
$node->nodeValue = replaceWords($node->nodeValue);
}
}
$wordReplacementsFrom = array('see');
$wordReplacementsTo = array('test');
function replaceWords($input) {
GLOBAL $wordReplacementsFrom, $wordReplacementsTo;
return str_replace($wordReplacementsFrom, $wordReplacementsTo, $input);
}
$dom = new DOMDocument;
// Supresses html parsing warnings / errors
libxml_use_internal_errors(true);
$dom->loadHTML('Edit the Expression & Text to <a href="#see">see</a> see matches. <a href="#see">see</a> see - <a href="#see">see</a> - ', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$i = 0;
while (is_object($item = $dom->getElementsByTagName("*")->item($i))) {
treatNode($item);
$i++;
}
// htmlspecialchars so that it appears as raw html to us while testing -- Do no use htmlspecialchars in production.
echo htmlspecialchars($dom->saveHTML());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment