PHP preg_split with two delimiters unless a delimiter is within quotes

不打扰是莪最后的温柔 提交于 2019-12-06 00:28:26

I was able to do this by adding quoted strings as a delimiter a-la

"(.*?)"| +|(=)

The quoted part will be captured. It seems like this is a bit tenuous and I did not test it extensively, but it at least works on your example.

Try

$array = preg_split('/(?: +|(=))(?=(?:[^"]*"[^"]*")*[^"]*$)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

The

(?=(?:[^"]*"[^"]*")*[^"]*$)

part is a lookahead assertion making sure that there is an even number of quote characters ahead in the string, therefore it will fail if the current position is between quotes:

(?=      # Assert that the following can be matched:
 (?:     # A group containing...
  [^"]*" #  any number of non-quote characters followed by one quote
  [^"]*" #  the same (to ensure an even number of quotes)
 )*      # ...repeated zero or more times,
 [^"]*   # followed by any number of non-quotes
 $       # until the end of the string
)

But why bother splitting?

After a look at this old question, this simple solution comes to mind, using a preg_match_all rather than a preg_split. We can use this simple regex to specify what we want:

"[^"]*"|\b\w+\b|=

See online demo.

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