I have a string like
$string = 'Some of "this string is" in quotes';
I want to get an array of all the words in the string which I can get by doing
$words = explode(' ', $string);
However I don't want to split up the words in quotes so ideally the end array will be
array ('Some', 'of', '"this string is"', 'in', 'quotes');
Does anyone know how I can do this?
You can use:
$string = 'Some of "this string is" in quotes';
$arr = preg_split('/("[^"]*")|\h+/', $string, -1,
PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r ( $arr );
Output:
Array
(
[0] => Some
[1] => of
[2] => "this string is"
[3] => in
[4] => quotes
)
RegEx Breakup
("[^"]*") # match quoted text and group it so that it can be used in output using
# PREG_SPLIT_DELIM_CAPTURE option
| # regex alteration
\h+ # match 1 or more horizontal whitespace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With