Dave's Brain

Browse - Programming Tips - How can I convert a string to an array of English words?

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"; } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.