i would like transform a string to array with pattern. But my regex give me the warning.
this is a string:
$string = typ="bar" title="Example" enabled=true count=true style="float: left; width: 30%;"
My regex:
$regex='/(.*?)[=\"|=](.*?)\"*\s*/';
preg_match_all($regex, $string1, $matchesreg, PREG_SET_ORDER);
Whith the regex is the output not correct. The last array must be split further $regex='/(.?)="(.?)"\s*/'; preg_match_all($regex, $string1, $matchesreg, PREG_SET_ORDER); The output
Array
(
[0] => Array
(
[0] => typ="bar"
[1] => typ
[2] => bar
) ...
[2] => Array
(
[0] => enabled=true count=true style="float: left; width: 30%;"
[1] => enabled=true count=true style
[2] => float: left; width: 30%;
)
)
My desired output like:
php
Array
(
[0] => Array
(
[0] => typ="bar"
[1] => typ
[2] => bar
)
[1] => Array
(
[0] => title="Example"
[1] => title
[2] => Example
)
[2] => Array
(
[0] => enabled=true
[1] => enabled
[2] => true
)
[3] => Array
(
[0] => count=true
[1] => count
[2] => true
)
[4] => Array
(
[0] => style="float: left; width: 30%;"
[1] => style
[2] => float: left; width: 30%;
)
)
You may use
preg_match_all('~([^\s=]+)=(?|"([^"]*)"|(\S+))~', $s, $m, PREG_SET_ORDER, 0)
See the PHP demo
Details
([^\s=]+)
- Group 1: one or more chars other than whitespace and =
=
- a =
char(?|"([^"]*)"|(\S+))
- a branch reset group matching either of
"([^"]*)"
- "
, then any 0 or more chars other than "
are captured into Group 2, and then "
is matched |
- or(\S+)
- Group 2: one or more non-whitespace chars.