3

I know /[\s]+/' splits a string by spaces. I am trying to expand this to ignore any spaces within double quotes. So I want Hello World to be split, but not "Hello World"

preg_split('/[\s]+/', $string) is the expression I am using in PHP.

gabz
  • 51
  • 8
  • how should this `'hello "again we met" and here "I am" '` be splitted? – RomanPerekhrest Apr 06 '17 at 19:58
  • I am only interested in ignoring double quoted strings. – gabz Apr 06 '17 at 20:03
  • @chris85 that's exactly what I needed. Thanks. – gabz Apr 06 '17 at 20:06
  • 1
    I am reopening this because @chris85 answer is good and from the dup question link, nobody mentions this easy way to do it (answer was match all) and his answer can be used in _preg_split()_ I encourage chris85 to post his comment as an answer. –  Apr 07 '17 at 05:08
  • @sln Thanks. I've moved comment to an answer. – chris85 Apr 07 '17 at 13:06

1 Answers1

5

You can use the PCRE verbs (*SKIP)(*FAIL) to tell the regex to skip specific parts of an expression. So:

".*?"(*SKIP)(*FAIL)|\s+

will skip double quoted strings. Here's a regex101 demo:

https://regex101.com/r/eBP67C/1/

You can read more about this here, http://www.rexegg.com/regex-best-trick.html#pcrevariation.

chris85
  • 23,846
  • 7
  • 34
  • 51