用给定div区域中的preg_replace替换php中的单词

问题描述 投票:2回答:3

想在我的网站上动态更换一些单词。

$content = preg_replace('/\bWord\b/i', 'Replacement', $content);

这到目前为止工作。但现在我只想改变div id =“content”里面的单词

我怎么做?

php regex wordpress
3个回答
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')]"

1
投票

使用the_content过滤器,您可以将它放在您的主题function.php文件中

add_filter('the_content', 'your_custom_filter');
function your_custom_filter($content) {
  $pattern = '/\bWord\b/i'
  $content = preg_replace($pattern,'Replacement', $content);
  return $content;
}

更新:仅当您使用WordPress时才适用。


1
投票

如果内容是动态驱动的,那么只需将$content的返回值回显到id为content的div中。如果内容是静态的,那么你必须在文本上使用这个PHP片段然后回显到div中,或者使用JavaScript(脏方法!)。

$content = "Your string of text goes here";
$content = preg_replace('/\bWord\b/i', 'Replacement', $content);

<div id="content">
    <?php echo $content; ?>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.