gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:46:15 26 4
gpt4 key购买 nike

想在我的网站上即时替换一些单词。

$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 - 在给定的div区域用preg_replace替换php中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3736427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com