【发布时间】:2011-04-13 18:43:06
【问题描述】:
想在我的网站上即时替换一些单词。
$content = preg_replace('/\bWord\b/i', 'Replacement', $content);
到目前为止有效。但现在我只想改变里面的单词 div id="内容"
我该怎么做?
【问题讨论】:
想在我的网站上即时替换一些单词。
$content = preg_replace('/\bWord\b/i', 'Replacement', $content);
到目前为止有效。但现在我只想改变里面的单词 div id="内容"
我该怎么做?
【问题讨论】:
$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')]"
【讨论】:
php+html+regex 上进行快速搜索,您将获得大量信息。
使用the_content过滤器,你可以把它放在你的主题function.php文件中
更新:这当然只适用于您使用 WordPress。
【讨论】:
如果内容是动态驱动的,那么只需将 $content 的返回值回显到带有内容 ID 的 div 中。如果内容是静态的,那么您必须在文本上使用这个 PHP sn-p 然后将返回回显到 div 中,或者使用 JavaScript(脏方法!)。
$content = "Your string of text goes here";
$content = preg_replace('/\bWord\b/i', 'Replacement', $content);
<div id="content">
<?php echo $content; ?>
</div>
【讨论】: