Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_split a string by spaces not between single quotes

I am trying to pref_split a string by spaces not between single quotes.

This is the string I am working with:

'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32

The following regex pattern successfully matches the space that I want to split by:

/\x20(?=[^']*('[^']*'[^']*)*$)\g

The problem I am having is that I wrote this string using http://www.regexr.com/ which is specific to JavaScript regex and I need this to work in PHP.

This is the PHP code I have so far but it is throwing an error:

preg_split("/\x20(?=[^']*('[^']*'[^']*)*$)/g", "'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32");

Error:

preg_split(): Unknown modifier 'g'

If I remove the / and /g I get the following error:

preg_match_all(): Compilation failed: nothing to repeat at offset 0

My guess is that for some reason the regex in PHP isn't matching any values so it is unable to split the string. Can someone help with how to properly do this?

Thank you.

like image 314
thestepafter Avatar asked Sep 07 '25 01:09

thestepafter


1 Answers

Remove the g (global) modifier from your regular expression.

preg_split("/\x20(?=[^']*('[^']*'[^']*)*$)/", "'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32");

Working Demo

Although your regular expression will work, you could use the following which makes this a lot easier to ignore the space characters in quotations.

$results = preg_split("/'[^']*'(*SKIP)(*F)|\x20/", $str);
print_r($results);

Explanation:

The idea is to skip content in single quotations. I first match the quotation followed by any character except ', followed by a single quotation, and then make the subpattern fail and force the regular expression engine to not retry the substring with another alternative with (*SKIP) and (*F) backtracking control verbs.

Output

Array
(
    [0] => 'physical memory %'=92%;99;100
    [1] => 'physical memory'=29.69GB;31.68;32;0;32
)
like image 56
hwnd Avatar answered Sep 10 '25 10:09

hwnd