maxisme
maxisme

Reputation: 4245

How can I split every space apart from when the space is within quotes?

I know How to split spaces into an array:

$array =  array_filter(preg_split('/\s+/',$a));

But if the string $a has quotes I want the regex to ignore all spaces within.


For example:

String:

@ IN TXT "V=SPF1 A MX IP4:x.x.x.x ~ALL"

Would split into array parts:

Upvotes: 0

Views: 42

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30995

preg_split

You can leverage PCRE verbs SKIP and FAIL that are used to discard patterns. The idea is to discard what are within quotes, so you can use a regex like this:

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

Working demo

enter image description here

However, if you want to use " or ' you can use this regex:

(["']).*?\1(*SKIP)(*FAIL)|\s+

$keywords = preg_split("/([\"']).*?\1(*SKIP)(*FAIL)|\s+/", $a);

preg_match_all

On the other hand, you can also use another regex to capture what you want by using something like this:

(".*"|'.*?'|\S+)

Working demo

$re = "/(\".*\"|'.*?'|\\S+)/"; 
$str = "@ IN TXT \"V=SPF1 A MX IP4:x.x.x.x ~ALL\" 'asdf asdf'"; 

preg_match_all($re, $str, $matches);

Upvotes: 1

Andris Leduskrasts
Andris Leduskrasts

Reputation: 1230

You can try\".*\"|\'.*\'|[^\s]*?(?=\s|$), that should match what you're looking for.

https://regex101.com/r/aZ7nJ8/2

A fairly crude way, but does the trick it and it contains the quotes, if you dont want them, you can always use lookaheads and lookbehinds.

Upvotes: 0

Related Questions