简体   繁体   English

preg_match的模式

[英]Pattern for preg_match

I have a string contains the following pattern "[link:activate/$id/$test_code]" I need to get the word activate, $id and $test_code out of this when the pattern [link.....] occurs. 我有一个包含以下模式“ [link:./.../$ id / $ test_code]”的字符串,当模式[link .....]出现时,我需要从中获取激活字,$ id和$ test_code。

I also tried getting the inside items by using grouping but only gets active and $test_code couldn't get $id. 我还尝试通过使用分组来获取内部项目,但仅处于活动状态,而$ test_code无法获得$ id。 Please help me to get all the parameter and action name in array. 请帮助我获取数组中的所有参数和动作名称。

Below is my code and output 下面是我的代码和输出

Code

function match_test()
{
    $string  =  "Sample string contains [link:activate/\$id/\$test_code] again [link:anotheraction/\$key/\$second_param]]] also how the other ationc like [link:action] works";
    $pattern = '/\[link:([a-z\_]+)(\/\$[a-z\_]+)+\]/i';
    preg_match_all($pattern,$string,$matches);
    print_r($matches);
}

Output 输出量

    Array
    (
        [0] => Array
            (
                [0] => [link:activate/$id/$test_code]
                [1] => [link:anotheraction/$key/$second_param]
            )

        [1] => Array
            (
                [0] => activate
                [1] => anotheraction
            )

        [2] => Array
            (
                [0] => /$test_code
                [1] => /$second_param
            )

    )

Is this what you are looking for? 这是你想要的?

/\\[link:([\\w\\d]+)\\/(\\$[\\w\\d]+)\\/(\\$[\\w\\d]+)\\]/

Edit: 编辑:

Also the problem with your expression is this part: (\\/\\$[az\\_]+)+ 同样,您表达的问题是这部分: (\\/\\$[az\\_]+)+

Although you have repeated the group, the match will only return one because it is still only one group declaration. 尽管您已经重复了该组,但是该匹配将仅返回一个,因为它仍然只是一个组声明。 The regex won't invent matching group numbers for you (Not that i've ever seen anyway). 正则表达式不会为您发明匹配的组号(无论如何我都没有见过)。

Try this: 尝试这个:

$subject = <<<'LOD'
Sample string contains [link:activate/$id/$test_code] again [link:anotheraction/$key/$second_param]]] also how the other ationc like [link:action] works
LOD;
$pattern = '~\[link:([a-z_]+)((?:/\$[a-z_]+)*)]~i';
preg_match_all($pattern, $subject, $matches);
print_r($matches);

if you need to have \\$id and \\$test_code separated you can use this instead: 如果您需要将\\$id\\$test_code分开,则可以使用以下代码:

$pattern = '~\[link:([a-z_]+)(/\$[a-z_]+)?(/\$[a-z_]+)?]~i';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM