PHP str_word_count() Function
Topic: PHP String ReferencePrev|Next
Description
The str_word_count()
function counts the number of words inside a string.
The following table summarizes the technical details of this function.
Return Value: | Returns an array or an integer, depending on the format chosen. |
---|---|
Version: | PHP 4.3.0+ |
Syntax
The basic syntax of the str_word_count()
function is given with:
The following example shows the str_word_count()
function in action.
Example
Run this code »<?php
// Sample string
$str = "The quick brown fox jumps over the lazy dog.";
// Counting words in the string
echo str_word_count($str);
?>
Parameters
The str_word_count()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to work on. |
format |
Optional. Specify the return value of this function. Possible values are:
|
charlist | Optional. Specifies a list of additional characters which will be considered as word. |
More Examples
Here're some more examples showing how str_word_count()
function actually works:
The following example returns an array having all the words found within the string.
Example
Run this code »<?php
// Sample string
$str = "The quick brown fox jumps over the lazy dog.";
// Getting words inside the string
$arr = str_word_count($str, 1);
print_r($arr);
?>
The following example returns an associative array containing all the words found inside the string as value, and their numeric position inside the string as key.
Example
Run this code »<?php
// Sample string
$str = "The quick brown fox jumps over the lazy dog.";
// Getting info about the words in the string
$arr = str_word_count($str, 2);
print_r($arr);
?>
The following example demonstrates how to use the charlist parameter in this function.
Example
Run this code »<?php
// Sample string
$str = "Hello everyone & welcome to our website.";
// Getting words inside the string
$arr = str_word_count($str, 1, "&");
print_r($arr);
?>