PHP String Functions

字符串是字符序列,比如 "Hello world!"。

PHP String Functions

在本节中,我们将学习常用的字符串操作函数。

PHP strlen() 函数

strlen() 函数返回字符串的长度,以字符计。

下例返回字符串 "Hello world!" 的长度:

Example

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

Run Instance

以上代码的输出是:12

Tip:strlen() 常用于循环和其他函数,在确定字符串何时结束很重要时。(例如,在循环中,我们也许需要在字符串的最后一个字符之后停止循环)。

对字符串中的单词计数

PHP str_word_count() 函数对字符串中的单词进行计数:

Example

<?php
echo str_word_count("Hello world!"); // 输出 2
?>

Run Instance

The output of the above code is:

2

Reverse the String

PHP strrev() Function Reverses the String:

Example

<?php
echo strrev("Hello world!"); // Output !dlrow olleH
?>

Run Instance

The output of the above code is:

!dlrow olleH

PHP strpos() Function

The strpos() function is used to search for a specified character or text within a string.

If a match is found, it will return the position of the first matching character. If no match is found, it will return FALSE.

The following example retrieves the text "world" from the string "Hello world!":

Example

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

Run Instance

The output of the above code is: 6.

Tip:In the above example, the position of the string "world" is 6. The reason it is 6 (not 7) is that the position of the first character in the string is 0, not 1.

Replace text in the string

The PHP str_replace() function replaces some strings with other strings in a string.

The following example replaces the text "world" with "Kitty":

Example

<?php
echo str_replace("world", "Kitty", "Hello world!"); // Output Hello Kitty!
?>

Run Instance

The output of the above code is:

Hello Kitty!

Complete PHP String Reference Manual

For a complete reference manual of string functions, please visit our PHP String Reference Manual.

This manual provides a brief description and example of each function!