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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀