PHP: str_word_count() function
Description
The str_word_count() function is used to count the number of words in a string.
Version:
(PHP 4 and above)
Syntax:
str_word_count(string_name, nformat, add_chars)
Parameter:
Name | Description | Required / Optional |
Type |
---|---|---|---|
string_name | The input string. | Required | String |
nformat | Specifies the return value of the str_word_count() function. Supported values : 0 - returns the number of words found. 1 - returns an array contains all the words found within the specified string. 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself. |
Optional | Integer |
add_chars | A list of additional characters which will be considered as 'word'. | Optional | String |
Return value:
An array or an integer, depending on the format chosen.
Value Type: Mixed.
*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.
Pictorial Presentation
Example:
<?php
$string_name='Welcome to w3resource.com';
print_r(str_word_count($string_name,0));
echo '<br>';
print_r(str_word_count($string_name,1));
echo '<br>';
print_r(str_word_count($string_name,2));
?>
Output :
5
Array ( [0] => Welcome [1] => to [2] => w [3] => resource [4] => com )
Array ( [0] => Welcome [8] => to [11] => w [13] => resource [22] => com )
View the example in the browser
See also
Previous: str_split
Next: strcasecmp
PHP: Tips of the Day
PHP: Remove first 4 characters of a string with PHP
You could use the substr function to return a substring starting from the 5th character:
$str = "The quick brown fox jumps over the lazy dog." $str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."
Ref : https://bit.ly/2LJDLQx
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework