Hướng dẫn
Quảng cáo

Hàm str-word-count() trong PHP

Hướng dẫn cách sử dụng hàm str-word-count() trong lập trình PHP

Tác dụng của hàm str-word-count()

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:

str_word_count(string, format, charlist);

The following example shows the str_word_count() function in action.

<?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:

  • 0 – Returns the number of words found. Default value.
  • 1 – Returns an array containing all the words found inside the 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.
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.

<?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.

<?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.

<?php
// Sample string
$str = "Hello everyone & welcome to our website.";

// Getting words inside the string
$arr = str_word_count($str, 1, "&");
print_r($arr);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements