views:

99

answers:

3

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?

A: 
Alex
No, i have a complete page generating dynamically, wit h some divs. And i want to change for example "Banana" into "Orange" but only in the div with the id content, and dont change it if its in div id recipe or id fruits
kalimero
A: 
$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')]"
Wrikken
Hello wrikken, i have the whole page already in $content, comes out of a wordpress database. so the DomDocument is not need, i just need the regex for the right pattern. but thanks so far!
kalimero
A _parser_ is needed, you cannot reliably alter HTML with regexes without the possibility of it breaking. Do a quick search here on `php+html+regex` and you'll be shared a wealth of information.
Wrikken
PHPQuery works very well for this as well: http://code.google.com/p/phpquery/
Gipetto
A: 

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.

Darren