douxin2011 2014-12-01 20:51
浏览 56
已采纳

Regexp在字符串PHP中搜索精确短语

i have an array containing some phrases:

$phrases = array(
  'phrase number one',
  'phrase number two',
  'phrase three',
  'phrase foo',
  'bar (foo 1.2.3)'
);

$text may contain part of phrase or exact phrase or phrase in the bbcode tags like this:

$text = '
  [b]phrase number one[/b] 
  [color="red"]phrase foo[/color]
  phrase three
  [b][color="red"]phrase foo[/color][/b]
  Lorem ipsum...
  [u][color="green"]phrase three[/color][/u]
  [url="http://example.com"]bar (foo 1.2.3)[/url]
  [url="http://example.com"][b]bar (foo 1)[/b][/url] dolor sit amet...
  phrase number two
';

i need to exclude that and search only exact phrase without bbcodes around it and replace: "phrase" => [other_bbcode]phrase[/other_bbcode]

foreach($phrases AS $phrase)
{
   $phrase = preg_quote($phrase, "#");
   if(preg_match('#(' . $phrase . ')+?#si', $text, $matches))
   {
      $text = preg_replace('#' . $matches[0] . '#i', '[other_bbcode]$matches[0][/other_bbcode]', $text);
   }
}

phrase three and phrase number two => replace
the rest text => stay as is
how to exclude phrases in bbcodes?
Thanks

  • 写回答

1条回答 默认 最新

  • doze79040 2014-12-02 08:55
    关注

    This can be done in three steps.

    A. Isolate. Remove all formatted strings from the text, place them in a buffer and replace with some kind of placeholder:

    $buf = [];
    
    do {
        $text = preg_replace_callback('~\[(\w+).+?\[/\1\]~', function($m) use(&$buf) {
            $buf []= $m[0];
            return '@' . (count($buf) - 1) . '@';
        }, $text, -1, $count);
    } while($count);
    

    B. Replace. Construct a regex from the phrases array and replace it in the "clean" text:

    $re = implode('|', array_map(function($x) {
        return '(' . preg_quote($x, '~') . ')';
    }, $phrases));
    
    $text = preg_replace("~$re~", '[new]$0[/new]', $text);
    

    C. De-isolate. Replace placeholders created on step A with their values from the buffer:

    do {
        $text = preg_replace_callback('~@(\d+)@~', function($m) use($buf) {
            return $buf[$m[1]];
        }, $text, -1, $count);
    } while($count);
    

    Another (and more robust in the long run) option is to convert bbcodes to xml and use DOM methods to walk the tree and manipulate its nodes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)