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.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题