【问题标题】:Replacing words in php with preg_replace in a given div area在给定的div区域中用preg_replace替换php中的单词
【发布时间】:2011-04-13 18:43:06
【问题描述】:

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

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

到目前为止有效。但现在我只想改变里面的单词 div id="内容"

我该怎么做?

【问题讨论】:

    标签: php regex wordpress


    【解决方案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')]"
    

    【讨论】:

    • 你好 wrikken,我的整个页面已经在 $content 中,来自 wordpress 数据库。所以不需要 DomDocument,我只需要正确模式的正则表达式。但是到目前为止,谢谢!
    • 需要一个解析器,你不能用正则表达式可靠地改变HTML,而不会破坏它。在php+html+regex 上进行快速搜索,您将获得大量信息。
    【解决方案2】:

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

    add_filter('the_content', 'your_custom_filter'); 功能 your_custom_filter($content) { $pattern = '/\bWord\b/i' $content = preg_replace($pattern,'替换', $content); 返回$内容; }

    更新:这当然只适用于您使用 WordPress。

    【讨论】:

      【解决方案3】:

      如果内容是动态驱动的,那么只需将 $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>
      

      【讨论】:

      • 不,我有一个动态生成的完整页面,其中包含一些 div。而且我想将例如“香蕉”更改为“橙色”,但仅在具有 id 内容的 div 中,如果它在 div id 食谱或 id 水果中,则不要更改它
      猜你喜欢
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2023-03-17
      • 2015-05-19
      • 2022-01-25
      相关资源
      最近更新 更多