W3Schools.com

PHP str_word_count() Function


PHP String Reference Complete PHP String Reference

Definition and Usage

The str_word_count() function counts the number of words in a string.

Syntax

str_word_count(string,return,char)

Parameter Description
string Required. Specifies the string to check
return Optional. Specifies the return value of the str_word_count() function.

Possible values:

  • 0 - Default. Returns the number of words found
  • 1 - Returns an array with the words from the string
  • 2 - Returns an array where the key is the position of the word in the string, and value is the actual word
char Optional. Specifies special characters to be considered as words.

Note: This parameter was added in PHP 5.1



Example 1

<?php
echo str_word_count("Hello world!");
?>

The output of the code above will be:

2


Example 2

<?php
print_r(str_word_count("Hello world!",1));
?>

The output of the code above will be:

Array
(
[0] => Hello
[1] => world
)


Example 3

<?php
print_r(str_word_count("Hello world!",2));
?>

The output of the code above will be:

Array
(
[0] => Hello
[6] => world
)


Example 4

str_word_count() without and with the char parameter:

<?php
print_r(str_word_count("Hello world & good morning!",1));
print_r(str_word_count("Hello world & good morning!",1,"&"));
?>

The output of the code above will be:

Array
(
[0] => Hello
[1] => world
[2] => good
[3] => morning
)

Array
(
[0] => Hello
[1] => world
[2] => &
[3] => good
[4] => morning
)


PHP String Reference Complete PHP String Reference
WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
Download XML Editor
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE