Ted pottel
Ted pottel

Reputation: 6983

PHP: Trying to figure out how to extract words from a string

I would like to create an array of all the words in a string. I tried to Google but only found str_split, which does not separate the words.

Upvotes: 2

Views: 9066

Answers (5)

Dan B
Dan B

Reputation: 411

You don't need to do-it-yourself: you can easily extract the words from a string using the built-in PHP function str_word_count(). Use format 1 or 2, thus:

$words = str_word_count("lorem ipsum dolor", 1);

// => ["lorem", "ipsum", "dolor"]

(Yes, it'd be more intuitive to have two appropriately-named functions rather than one that does everything, so it's no wonder you didn't come across it.)

Note that for the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with, characters ' and -.
Also note that multibyte locales are not supported.

Upvotes: 1

Suvier
Suvier

Reputation: 59

I prefer the solution

$string  = "    a   bunch    of  words   ";
$array_of_words = preg_split("/\s/", $string, -1, PREG_SPLIT_NO_EMPTY);

that gives

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(5) "bunch"
  [2]=>
  string(2) "of"
  [3]=>
  string(5) "words"
}

IMO is more elegant.

Upvotes: 1

Alain
Alain

Reputation: 36944

If your words are separated with several spaces, tabs or new lines, you may want to ignore them.

$string  = "    a   bunch    of  words   ";
$string = trim(preg_replace('!\s+!', ' ', $string));
$array_of_words = explode(" ", $string);

Gives:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(5) "bunch"
  [2]=>
  string(2) "of"
  [3]=>
  string(5) "words"
}

Upvotes: 7

dflash
dflash

Reputation: 41

You can typically use explode():

$string  = "a bunch of words";
$array_of_words = explode(" ", $string);

http://php.net/manual/en/function.explode.php

Upvotes: 1

Simon M
Simon M

Reputation: 2941

Try using this:

$new_array = explode(' ', $your_string);

Now $new_array contains a string for every word in $your_string.

Upvotes: 0

Related Questions