开发者

regex preg_match|preg_match_all in php

I'm trying to come up with a regex that constructs an array that looks like the one below, from the following string

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}';
开发者_如何学Go

So far I have /^(\*{0,3})(.+)\[(.*)\]((?:{[a-z ]+})?)$/

Array
(
    [0] => Array
        (
            [0] => Hello world [something here]{optional}{optional}{optional}{n possibilities of this}
            [1] => 
            [2] => Hello world
            [3] => something here
            [4] => {optional}
            [5] => {optional}
            [6] => {optional}
            [7] => ...
            [8] => ...
            [9] => {n of this}
        )
)

What would be a good approach for this? Thanks


I think you will need two steps for this.

  1. (.+)\[(.+)\](.+) will get you Hello world, something here, and {optional}...{optional}.

  2. Applying \{(.+?)\} to the last element from the previous step will get you optional params.


Here is an approach which I believe is even cleaner than you have asked for:

Code: (PHP Demo) (Pattern Demo)

$str = 'Hello world [something here]{optional}{optional}{optional}{n possibilities of this}';

var_export(preg_split('/ *\[|\]|(?=\{)/', $str, 0, PREG_SPLIT_NO_EMPTY));

Output:

array (
  0 => 'Hello world',
  1 => 'something here',
  2 => '{optional}',
  3 => '{optional}',
  4 => '{optional}',
  5 => '{n possibilities of this}',
)

preg_split() will be breaking your string on three possible occurrences (removing these occurrences in the process):

  • *\[ means zero or more spaces followed by a opening square bracket.
  • \] means a closing square bracket.
  • ?=\{) means a zero-length character (the position just before...) an opening curly bracket.

*My pattern generates an empty element between ] and {. To eliminate this useless element, I added the PREG_SPLIT_NO_EMPTY flag to the function call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜