想要在我的網站上隨時替換某些單詞。使用preg_replace替換給定div區域中的單詞
$ pattern ='/ \ bWord \ b/i'; $ content = preg_replace($ pattern,'Replacement',$ content);
到目前爲止工作。但現在我只想改變裏面的文字 div id =「content」
我該怎麼做?
想要在我的網站上隨時替換某些單詞。使用preg_replace替換給定div區域中的單詞
$ pattern ='/ \ bWord \ b/i'; $ content = preg_replace($ pattern,'Replacement',$ content);
到目前爲止工作。但現在我只想改變裏面的文字 div id =「content」
我該怎麼做?
$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')]"
如果內容是動態驅動的,那麼只需將$ content的返回值回顯到帶有內容標識的div中即可。如果內容是靜態的,那麼你將不得不在文本上使用這個PHP snippit,然後將回顯放回到div中,或者使用JavaScript(髒方法!)。
$content = "Your string of text goes here";
$pattern = '/\bWord\b/i';
$content = preg_replace($pattern,'Replacement',$content);
<div id="content">
<?php echo $content; ?>
</div>
不,我有一個完整的頁面動態生成,用一些div。我想改變例如「香蕉」爲「橙」,但只有在與ID內容的div,並且不改變它,如果它在div id食譜或id水果 – kalimero 2010-09-17 14:59:55
使用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; }
UPDATE:這僅適用如果您使用當然WordPress的。
你好wrikken,我已經整個頁面已經在$內容,來自wordpress數據庫。所以DomDocument是不需要的,我只需要正確的模式的正則表達式。但迄今爲止感謝! – kalimero 2010-09-17 15:32:58
需要一個_parser_,你不能用正則表達式可靠地改變HTML,而不會破壞它。在這裏快速搜索'php + html + regex',你將會分享豐富的信息。 – Wrikken 2010-09-17 15:47:14
PHPQuery也適用於此:http://code.google.com/p/phpquery/ – Gipetto 2010-09-18 06:40:20