We can use str_word_count string function to get all details of words present in the string. Here is one example.

$str = "Welcom to plus2net PHP section";
$position = str_word_count($str);
echo $position; // output is 6

Simple counting of words can be done like this, however we can more information on words with optional parameter like this.

0 Number of words used in the string
1 Array of words used inside the string
2 Array of words with their position in the string

Here is one example with integer format = 1 , we will get an array with words as element of the array. Here is the output.

$str = "Welcom to plus2net PHP section";
$position = str_word_count($str,1);
echo print_r($position);

Output of this is here

Array ( [0] => Welcom [1] => to [2] => plus [3] => net [4] => PHP [5] => section ) 1

Now let us try with format value as 2

$position = str_word_count($str,2);

Output is here

Array ( [0] => Welcom [7] => to [10] => plus [15] => net [19] => PHP [23] => section ) 1

Along with the words used the key of the array is numeric position of the word inside the string.
We can specify additional chars which can be considered as a word.

$position = str_word_count($str,1,'2');

Here 2 will be considered as part of the word so now the word plus2net will be treated as single word..

Be the first to post comment on this article :

PHP String Functions

Post Comment This is for short comments only. Use the forum for more discussions.

HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2015 All rights reserved worldwide Privacy Policy Disclaimer