- var_dump: documentation ( source)
- in_array: documentation ( source)
<?php
function get_phrases($sentence) {
$inQuotes = false;
$quoteChars = ['"', "'"];
$separators = [' ', "\n"];
$phrase = null;
foreach ((string) $sentence as $i => $t) {
if (!$inQuotes && in_array($t, $quoteChars)) {
// Opening quote
$inQuotes = $t;
} elseif ($inQuotes && $t == $inQuotes) {
// Closing quote
$inQuotes = false;
} elseif (!$inQuotes && in_array($t, $separators)) {
yield $phrase; // or add to an array in pre-5.5
$phrase = null;
} else {
$phrase .= $t;
}
}
}
var_dump(get_phrases('Hello world'));
var_dump(get_phrases("I am a 'foo bar'"));