Created
March 20, 2015 16:55
-
-
Save scottchiefbaker/10d5871a6a5743297bdc to your computer and use it in GitHub Desktop.
PHP version of Perl's qw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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