PHP String Functions
PHP has many built-in string functions.
String Length
The PHP strlen() function returns the length of a string.
Example
Return the length of the string "Hello world!":
echo strlen("Hello world!");
Try it Yourself »
Word Count
The PHP str_word_count() function counts the
number of words in a string.
Example
Count the number of word in the string "Hello world!":
echo str_word_count("Hello world!");
Try it Yourself »
Search For Text Within a String (PHP 8)
The PHP
str_contains() function checks if a string contains a specific
substring.
If a match is found, the function returns a boolean true. If no match is found, it will return a boolean false.
Example
Search for the text "love" in the string "I really love PHP!":
$txt = "I really love PHP!";
var_dump(str_contains($txt, "love"));
Try it Yourself »
Note: This function performs a case-sensitive search.
The following example will return a boolean false, because "Love" is not found in the main string:
Example
Search for the text "Love" in the string "I really love PHP!":
$txt = "I really love PHP!";
var_dump(str_contains($txt, "Love"));
Try it Yourself »
Search For Text Within a String (PHP 7)
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return false.
Note: This function performs a case-sensitive search.
Example
Search for the text "world" in the string "Hello world!":
echo strpos("Hello world!", "world");
Try it Yourself »
Tip: The first character position in a string is 0 (not 1).
Complete PHP String Reference
For a complete reference of all string functions, go to our complete PHP String Reference.