Question

I'm writing a recursive function and I'm getting into trouble on the regular expression part...

hopefully one of you kind people can help...

give a single string with contents such as below...

setDynamicFields=[product_model=1;attribute_id=10];setDynamicFields=[product_model=1;attribute_id=10];joinTable=suppliers;

I need to split this by semi-colons however I need to ignore those semi-colons found between [ and ] i.e. setDynamicFields=[product_model=1;attribute_id=10] should be split out in tact so I can set setDynamicFields as a key and [product_model=1;attribute_id=10] as a value

I've tried the following...

$fields = preg_split("/(\b(?!=[\[])[a-zA-Z_][a-zA-Z_0-9]*\b(?![\]]))/",$line);

$fields = preg_split("/(?!=\[)(;)(?!\])/",$line);

Not having much luck :-(

Any takers?

many thanks,

Robert

Was it helpful?

Solution

split by semi-colons not found between opening and closing brackets

If the brackets are always balanced and you want to split you can use a regex like:

;(?![^][]*\])

In PHP written something like:

$fields = preg_split('/;(?![^][]*\])/', $line);

OTHER TIPS

You could use:

.*?(\[.*?\])?;

This will match everything up to a semi-colon, optionally consuming anything that exists in square brackets until the next semi-colon is found

I'd use

/([^;]*)?=(\[.+?\])|([^;]*?)=(.*?);/g

See the example@regex101.

The g-flag is only necessary if your input is not on one line.
Also, don't use preg_split for this, use preg_match_all, see this demo (be sure to hit preg_match_all on the right) for the results. See the manual for preg_match_all for further infos regarding the usage.

This will cover both eventualities in your input string: the [] being present or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top