简体   繁体   中英

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.

I also tried getting the inside items by using grouping but only gets active and $test_code couldn't get $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\\_]+)+

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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