want to replace some words on the fly on my website.
$pattern = '/\bWord\b/i'; $content = preg_replace($pattern,'Replacement',$content);
That works so far. But now i want only change the the words which are inside div id="content"
How do i do that?
want to replace some words on the fly on my website.
$pattern = '/\bWord\b/i'; $content = preg_replace($pattern,'Replacement',$content);
That works so far. But now i want only change the the words which are inside div id="content"
How do i do that?
$dom = new DOMDocument();
$dom->loadHTML($html);
$x = new DOMXPath($dom);
$pattern = '/foo/';
foreach($x->query("//div[@id='content']//text()") as $text){
preg_match_all($pattern,$text->wholeText,$occurances,PREG_OFFSET_CAPTURE);
$occurances = array_reverse($occurances[0]);
foreach($occurances as $occ){
$text->replaceData($occ[1],strlen($occ[0]),'oof');
}
//alternative if you want to do it in one go:
//$text->parentNode->replaceChild(new DOMText(preg_replace($pattern,'oof',$text->wholeText)),$text);
}
echo $dom->saveHTML();
//replaces all occurances of 'foo' with 'oof'
//if you don't really need a regex to match a word, you can limit the text-nodes
//searched by altering the xpath to "//div[@id='content']//text()[contains(.,'searchword')]"
use the_content filter, you can place it in your themes function.php file
add_filter('the_content', 'your_custom_filter');
function your_custom_filter($content) {
$pattern = '/\bWord\b/i'
$content = preg_replace($pattern,'Replacement', $content);
return $content;
}
UPDATE: This applies only if you are using WordPress of course.