简体   繁体   中英

Match all repeated regex patterns in php

Can anybody please help with this reg ex problem?

I want to get all components of this example text:

filter:bundesland|4-berlin|6-hamburg|3-nordrhein-westphalen:stadt|3-koeln|2-dresden:typ|5-schule|2-kindergarten|6-hort

I am matching this string using:

filter(:(bundesland|stadt|typ)(\|\d-[a-z\s-]*)*)*

I need to get something like this as a result:

Array
(
    ['bundesland'] => Array
        (
            [1] => 4
            [2] => 6
            [3] => 3
        )

    ['stadt'] => Array
        (
            [1] => 3
            [2] => 2
        )

    ['typ'] => Array
        (
            [1] => 5
            [2] => 2
            [3] => 6
        )

)

(I don't care about the labels. Just need the IDs)

You can try this:

$pattern = '~(?:(?:filter|\G(?!\A)):(\w+)\||\G(?!\A))(\d+)[^\d:\s]*~';

$result = array();

if (preg_match_all($pattern, $str, $matches, PREG_SET_ORDER)) {
    foreach ($matches as $m) {
        if (!empty($m[1])) $current = $m[1];
        $result[$current][] = $m[2];
    }
}
print_r($result);

You can use this PHP code:

$s = 'filter:bundesland|4-berlin|6-hamburg|3-nordrhein-westphalen:stadt|3-koeln|2-dresden:typ|5-schule|2-kindergarten|6-hort';
$result = array();
preg_replace_callback('~:(\w+)([^:]+)~', function ($m) use (&$result) {
        preg_match_all('/(?<=\|)[0-9]+/', $m[2], $sm); $result[$m[1]] = $sm[0]; }, $s);
print_r($result);

OUTPUT:

Array
(
    [bundesland] => Array
        (
            [0] => 4
            [1] => 6
            [2] => 3
        )
    [stadt] => Array
        (
            [0] => 3
            [1] => 2
        )
    [typ] => Array
        (
            [0] => 5
            [1] => 2
            [2] => 6
        )
)

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