PHP preg_match_all,check&爆炸

时间:2015-10-06 12:02:42

标签: php regex recursion

我想检查一下' n'爆炸这个字符串:

{$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/.../fooN}

为:

var_name[0] => 'gallery',
modul_name[0] => 'pager',
3[0] => 'collectionName',
4[0] => 'imageName',
5[0] => 'manual'
...
N[0] => 'fooN'

我做了以下正则表达式:

/{\$(?P<var_name>[^#]+)#(?P<module_name>[^\/]+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+))?)?)?)?)?}/

,但它太难看了,最多只支持五个参数。 请帮我做一个递归部分来提取所有参数。

ps:是的,我可以将其拆分为 var_name module_name 参数部分,然后我可以分解参数分开的&#39; /&#39;,但我不喜欢它。

2 个答案:

答案 0 :(得分:3)

您可以使用preg_split()

<强>正则表达式:

preg_split('@([$#])|[{}/]+@', $text)

丢弃数组中的第一项和第三项。

ideone Demo

编辑: 要在评论中反映OP指定的新条件(不在问题中):它应验证语法^\{\$\w+#\w+(?:/\w*)$并在< em> var ,模块参数独立。

<强>正则表达式:

~\G(?(?=^)\{\$(\w++)#(\w++)(?=[\w/]+}$))/\K\w*+~

<强>代码:

// http://stackoverflow.com/q/32969465/5290909

$pattern = '@\G(?(?=^)\{\$(\w++)#(\w++)(?=[\w/]+}$))/\K\w*+@';
$text = '{$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/fooN}';

$result = preg_match_all($pattern, $text, $matches);

if ($result === 0) {
    // is invalid, does not match '~^\{\$\w+#\w+(?:/\w*)+$~'
    echo "Invalid text";
} else {
    // Assign vars (only to clarify)
    $module_name = array_pop($matches)[0];
    $var_name = array_pop($matches)[0];
    $parameters = $matches;

    echo "VAR NAME: \t'$var_name'\nMODULE:  \t'$module_name'\nPARAMETERS:\n";
    print_r($matches);
}

<强>输出:

VAR NAME:   'gallery'
MODULE:     'pager'
PARAMETERS:
Array
(
    [0] => collectionName
    [1] => imageName
    [2] => manual
    [3] => no_effect
    [4] => foo1
    [5] => foo2
    [6] => fooN
)

ideone Demo

答案 1 :(得分:2)

{\$([^#]+)#|\G(?!^)([^\/]+)\/|\G(?!^)(.*?)}$

您可以简单地进行匹配并抓住groups。请参阅演示。

https://regex101.com/r/cJ6zQ3/18

$re = "/{\\$([^#]+)#|\\G(?!^)([^\\/]+)\\/|\\G(?!^)(.*?)}$/m"; 
$str = "{\$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/.../fooN}"; 

preg_match_all($re, $str, $matches);