Date: 2010apr20
Language: php
Q. How can I convert a string to an array of English words?
A. Here is a function that does that:
function getWords($a) {
return preg_split('/\W+/', $a, -1, PREG_SPLIT_NO_EMPTY);
}
# One problem: turns apostrophes into two words - eg "Apple's iPad"
# becomes ["Apple", "s", "iPad"] so an alternative is:
function getWords($a) {
return preg_split('/[\s,;\-\.]+/', $a, -1, PREG_SPLIT_NO_EMPTY);
}
function exampleUse() {
$str = "One two three.";
$words = getWords($str);
foreach ($words as $word) {
print "word=$word\n";
}
}
| What this info useful to you? You can donate to say thanks |
Add a comment
Sign in to add a comment