how to know how many words a String has in php?

2

Hello friend, I have a small PHP exercise in which I have to request the user's name and tell him how many words have his full name and that's it.

but I do not constrict it I have this following code:

$textosolicitado = print "var nombre= prompt('cual es tu nombre');";


echo "Tu nombre tiene:";
echo str_word_count($textosolicitado);//will return the number of words in a string
    
asked by simon 20.04.2017 в 02:19
source

1 answer

3

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.

    
answered by 20.04.2017 / 03:18
source