php - How can I split every space apart from when the space is within quotes? -
i know how split spaces array:
$array = array_filter(preg_split('/\s+/',$a));
but if string $a
has quotes want regex ignore spaces within.
for example:
string:
@ in txt "v=spf1 mx ip4:x.x.x.x ~all"
would split array parts:
- @
- in
- txt
- "v=spf1 mx ip4:x.x.x.x ~all" (don't mind if contains ' " ' or not)
preg_split
you can leverage pcre
verbs skip
, fail
used discard patterns. idea discard within quotes, can use regex this:
".*?"(*skip)(*fail)|\s+
however, if want use "
or '
can use regex:
(["']).*?\1(*skip)(*fail)|\s+ $keywords = preg_split("/([\"']).*?\1(*skip)(*fail)|\s+/", $a);
preg_match_all
on other hand, can use regex capture want using this:
(".*"|'.*?'|\s+)
$re = "/(\".*\"|'.*?'|\\s+)/"; $str = "@ in txt \"v=spf1 mx ip4:x.x.x.x ~all\" 'asdf asdf'"; preg_match_all($re, $str, $matches);
Comments
Post a Comment