Skip to content

Instantly share code, notes, and snippets.

@scottchiefbaker
Created March 20, 2015 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottchiefbaker/10d5871a6a5743297bdc to your computer and use it in GitHub Desktop.
Save scottchiefbaker/10d5871a6a5743297bdc to your computer and use it in GitHub Desktop.
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