You are here

16 September 2013

How to split words in string to an array using regular expressions. You can use this for search indexing for an example.

Source code viewer
  1. $input = 'How to split words in string to an array using regex.';
  2. $output = array();
  3.  
  4. preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $input, $matches, PREG_SET_ORDER);
  5. foreach ($matches as $match) {
  6. $phrase = false;
  7. // Strip off phrase quotes.
  8. if ($match[2]{0} == '"') {
  9. $match[2] = substr($match[2], 1, -1);
  10. $phrase = true;
  11. }
  12. $words = trim($match[2], ',?!();:-');
  13. $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
  14. foreach ($words as $word) {
  15. $output[] = trim($word, " ,!?.");
  16. }
  17. }
Programming Language: PHP