Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP version of Perl's qw
function qw($str,$return_hash = false) {
$str = trim($str);
// Word characters are any printable char
$words = str_word_count($str,1,"!\"#$%&'()*+,./0123456789-:;<=>?@[\]^_`{|}~");
if ($return_hash) {
$ret = array();
$num = sizeof($words);
// Odd number of elements, can't build a hash
if ($num % 2 == 1) {
return array();
} else {
// Loop over each word and build a key/value hash
for ($i = 0; $i < $num; $i += 2) {
$key = $words[$i];
$value = $words[$i + 1];
$ret[$key] = $value;
}
return $ret;
}
} else {
return $words;
}
}
/*
$str = "Leonardo Donatello Michelangelo Raphael";
$array = qw($str);
$str = "
Leonardo Blue
Donatello Purple
Michelangelo Orange
Raphael Red
";
$turtles = qw($str,true);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment