Using php to detect characters outside quotes

I need to split a string into two using a delimiter character. All I have to do is use the explode () function ... I know.

But here's what I'm trying to do: I need to split the string using a separator, but if the separator is enclosed in quotation marks, it should be ignored.

Let's say my separator is a hyphen (-), and I need to break the following line:

"Big yellow house - near the lake

The first hyphen should be ignored because it is enclosed in quotation marks, so I would get two lines, such as:

1. "Big yellow house."
2. next to the lake

And he should also be able to detect hidden quotes.

For example: he does not like it because he is not here.

In this case, the hyphen is not enclosed in quotation marks, so the string must be separated.

Any thoughts?

+6
source share
2 answers

you can use

'[^'\\]*(?:\\.[^'\\]*)*'(*SKIP)(?!)|- 

Watch the regex demo

Part '[^'\\]*(?:\\.[^'\\]*)*' will correspond to single quotes and any escaped objects, and (*SKIP)(?!) will force the regex mechanism to continue to search for matches after last index length +.

And here is the IDEONE demo :

 $re = "/'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'(*SKIP)(?!)|-/"; $strs = array("The 'big-yellow' house-is near the lake", "He doesn\'t like it because-he isn\'t from here."); foreach ($strs as $str) { $result = preg_split($re, $str); print_r($result); } 

Output:

Array( [0] => The 'big-yellow' house [1] => is near the lake) and Array( [0] => He doesn\'t like it because [1] => he isn\'t from here.) .

+2
source

Maybe something like this?

 function fsplit($str, $delimiter) { $result = array(); $inside_quote = false; $last_index = 0; for($i=0; $i<strlen($str);$i++) { if($str[$i] == $delimiter and !$inside_quote) { array_push($result, substr($str, $last_index, $i - $last_index)); $last_index = $i+1; } elseif($str[$i] == "'") { $inside_quote = !$inside_quote; } } return $result; } 
+1
source

All Articles