簡體   English   中英

匹配php中所有重復的正則表達式模式

[英]Match all repeated regex patterns in php

有人可以幫忙解決此正當問題嗎?

我想獲取此示例文本的所有組件:

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

我使用以下方式匹配此字符串:

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

我需要得到這樣的結果:

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

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

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

)

(我不在乎標簽。只需要ID)

您可以嘗試以下方法:

$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);

您可以使用以下PHP代碼:

$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);

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM