You can use str_word_count
, available from PHP version 4, and 5 and 7.
The function receives as your first parameter your string
, as second an optional value to return only the count of the words 0
or default nothing, 1
returns an array with all the words found and their order, and 2
that also returns an array but that shows the words found and the position in which it is inside the string you passed.
Like this:
php > echo str_word_count('Hello world!');
2
With a value 1
as formato
:
php > print_r(str_word_count('Hello world!', 1));
Array
(
[0] => Hello
[1] => world
)
Passing 2
, this time shows the position within your string
where the second word starts:
php > print_r(str_word_count('Hello world!', 2));
Array
(
[0] => Hello
[6] => world
)
The third and optional parameter is the charlist
that can be used to add an additional list of characters that will be used as words.