Replacing words in php with preg_replace in a given div area

Want to replace some words on the fly on my website.

$content = preg_replace('/bWordb/i', 'Replacement', $content);

That works so far. But now i want only change the the words which are inside
div id=”content”

Read More

How do i do that?

Related posts

Leave a Reply

3 comments

  1. $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')]"
    
  2. 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 = '/bWordb/i'
      $content = preg_replace($pattern,'Replacement', $content);
      return $content;
    }
    

    UPDATE: This applies only if you are using WordPress of course.

  3. If the content is dynamically driven then just echo the return value of $content into the div with id of content. If the content is static then you’ll have to either use this PHP snippet on the text then echo out the return into the div, or use JavaScript (dirty method!).

    $content = "Your string of text goes here";
    $content = preg_replace('/bWordb/i', 'Replacement', $content);
    
    <div id="content">
        <?php echo $content; ?>
    </div>