想要在我的网站上动态更换一些单词。
$content = preg_replace('/\bWord\b/i', 'Replacement', $content);
到目前为止这是有效的。但现在我只想改变里面的词 div id =“content”
我该怎么做?
答案 0 :(得分:1)
如果内容是动态驱动的,那么只需将$content
的返回值回显到内容为id的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>
答案 1 :(得分: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 :(得分: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时才适用。