PHP regex : split on unescaped delimiter

我的未来我决定 提交于 2019-11-29 12:14:16
Tim Pietzcker
preg_match_all(
    '/(                    # Match and capture...
     (?:                   # either:
      \\\\.                # an escaped character
     |                     # or:
      [^\\\\:]             # any character except : or \
     )+                    # one or more times
    )                      # End of capturing group 1
    :                      # Match a colon
    ((?:\\\\.|[^\\\\;])+); # Same for 2nd part with semicolons
    /x', 
    $inside, $pairs);

does this. It doesn't remove the backslashes, though. You can't do that in a regex itself; for this, you'd need a callback function.

To match the final element even if it doesn't end with a delimiter change the ; to (?:;|$) (same for the :). And to return empty elements as well change the + to a *.

You can do:

$inside = "key\:1:value\;1;key2:value2;key3:value3;";
$pairs = preg_split('/(?<!\\\\);/',$inside,-1,PREG_SPLIT_NO_EMPTY );
foreach($pairs as $pair) {
        list($k,$v) = preg_split('/(?<!\\\\):/',$pair);
        // $k and $v have the key and value respectively.
}

See it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!