dongqichang7988 2013-12-07 22:24
浏览 11
已采纳

Php,Regex,在字符串之间

I was trying to find a pattern for the following scenario:

Lets say i have this string:

someString[code]some code[/code]someString

Now some code can be anything, What i want to get is reserved words (break, class, etc), So for a real scenario this is a string:

someString
[code]
class someClass{}
[/code]
someString

// And again

someString
[code]
class someClass{}
[/code]
someString

So what i was trying to understand is how can i match all the reserved words that between all of the [code][/code] tags.

For example: [code]someReservedWord some text anotherReservedWord[/code] I only want to match someReservedWord and anotherReservedWord.

I was thinking to use preg_match_all So i can get all reserved words inside each [code][/code] and use PREG_OFFSET_CAPTURE to get their positions,

The only thing i can't figure out is the pattern, if anyone got idea i will be very thankful, Thank you all and have a nice day.

  • 写回答

2条回答 默认 最新

  • dongyun7571 2013-12-07 22:40
    关注

    You can use this:

    $pattern = <<<'LOD'
    ~ (?(DEFINE) (?<words> class | string | function ) )
    
    (?: \[code] | \G(?<!^) )
    (?: [^[]+? | \[(?!/code]) )*? \K
    \b \g<words> \b
    
    ~x
    LOD;
    
    preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
    
    print_r($matches[0]);
    

    pattern details:

    First at all we define a named group with all reserved words:

    (?(DEFINE) (?<words> class | string | function ) )
    

    The (?(DEFINE)...) syntax allows to define subpatterns out of the pattern itself. You can call the named group "words" later in the pattern with \g<words>.

    (?: [^[]+? | \[(?!/code]) )*? describes all the content before a reserved word. This subpattern can match all except the closing tag [/code] because you have the choice between "all that is not a [" or "a [ not followed by /code". Since it can match all, lazy quantifiers are used to stop the match when a reserved word is encountered.

    The entry point of the pattern is (?: \[code] | \G(?<!^) ). This enforce the match to begin with a [code] tag or to be contiguous to a precedent match.

    (\G is an anchor that means: "at the start of the string or contiguous to a precedent match". With the negative lookbehind (?<!^), you forbid the start of the string.)

    \K is a trick that resets all the matched content before it from the match result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错