Reputation: 573
I'm using the following code to split a string into an array of matches:
$text = 'text required name="first_name" label="First Name"';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);
print_r($matches);
The result is:
Array
(
[0] => Array
(
[0] => text
[1] => required
[2] => name=
[3] => "first_name"
[4] => label=
[5] => "First Name"
)
)
But I need the result to be:
Array
(
[0] => Array
(
[0] => text
[1] => required
[2] => name="first_name"
[3] => label="First Name"
)
)
I tried this but it didn't work:
preg_match_all('/="(?:\\\\.|[^\\\\"])*"|[^\s"]+/', $text, $matches);
Can anyone tell me where I'm going wrong? Thanks
Upvotes: 0
Views: 663
Reputation: 342
If you want to use preg_match_all
here's a working code:
$text = 'text required name="first_name" label="First Name"';
preg_match_all('([a-zA-Z_]*[=]["][a-zA-Z_]*["]|[a-zA-Z_]*[=]["][ a-zA-Z]*["]|[a-zA-Z]+)', $text, $matches);
print_r($matches);
Upvotes: 0
Reputation: 21489
You can use pattern /\s(?![\w\s]+\")/
in preg_split()
to split string by space that isn't in value.
$res = preg_split("/\s(?![\w\s]+\")/", $text);
Check result in demo
Upvotes: 2