Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex (preg_split): how do I split based on a delimiter, excluding delimiters included in a pair of quotes?

I split this:

1 2 3 4/5/6 "7/8 9" 10

into this:

1
2
3
4
5
6
"7/8 9"
10

with preg_split()

So my question is, how do I split based on a delimiter, excluding delimiters inside a pair of quotes?

I kind of want to avoid capturing the things in quotes first and would ideally like it to be a one liner.

like image 852
theamycode Avatar asked Jul 28 '14 21:07

theamycode


People also ask

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.

How to split list based on delimiter in Python?

Split by delimiter: split()Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.

What is Preg_split function in PHP?

The preg_split() function breaks a string into an array using matches of a regular expression as separators.


1 Answers

You can use the following.

$text = '1 2 3 4/5/6 "7/8 9" 10';
$results = preg_split('~"[^"]*"(*SKIP)(*F)|[ /]+~', $text);
print_r($results);

Explanation:

On the left side of the alternation operator we match anything in quotations making the subpattern fail, forcing the regular expression engine to not retry the substring using backtracking control with (*SKIP) and (*F). The right side of the alternation operator matches either a space character or a forward slash not in quotations.

Output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => "7/8 9"
    [7] => 10
 )
like image 106
hwnd Avatar answered Sep 21 '22 18:09

hwnd