php - 按空格和冒号拆分字符串,但如果在引号内则不拆分

标签 php regex preg-match preg-match-all preg-split

有这样一个字符串:

$str = "dateto:'2015-10-07 15:05' xxxx datefrom:'2015-10-09 15:05' yyyy asdf"

期望的结果是:

[0] => Array (
    [0] => dateto:'2015-10-07 15:05'
    [1] => xxxx
    [2] => datefrom:'2015-10-09 15:05'
    [3] => yyyy
    [4] => asdf
)

我得到的:

preg_match_all("/\'(?:[^()]|(?R))+\'|'[^']*'|[^(),\s]+/", $str, $m);

是:

[0] => Array (
    [0] => dateto:'2015-10-07
    [1] => 15:05'
    [2] => xxxx
    [3] => datefrom:'2015-10-09
    [4] => 15:05'
    [5] => yyyy
    [6] => asdf
)

也尝试使用 preg_split("/[\s]+/", $str) 但不知道如果值在引号之间如何转义。任何人都可以告诉我如何并请解释正则表达式。谢谢!

最佳答案

我会使用 PCRE 动词 (*SKIP)(*F),

preg_split("~'[^']*'(*SKIP)(*F)|\s+~", $str);

DEMO

关于php - 按空格和冒号拆分字符串,但如果在引号内则不拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33041330/

相关文章:

regex - 从日志文件中提取数据的 Shell 程序

php - 正则表达式检查另一个字符串中是否存在一个字符串

php - 将没有分隔符的字符串转换为关联多维数组

php - 如何将网站上不存在的链接重定向回主页

javascript - 如何以 php,html 多选项卡形式传递数据?

php - 动态自动选择,在其他地方更改图像

c# - 正则表达式需要识别句子之间没有空格的地方

Javascript——仅获取正则表达式匹配的可变部分

php - preg_match+多模式

php - 更新 id 等于 3 的表,并在 updatecount 列中的现有值上加一