PHP String Functions
Working with text is so common that PHP ships with many built-in functions for it. This page introduces a few you will reach for again and again.
strlen() - Return the Length of a String
Call strlen() when you need to know how long a string is.
strlen() example
Spaces and punctuation count too, so "Hello world!" has a length of 12:
Output: PHP script
<?php
echo strlen("Hello world!");
?>
str_word_count() - Count Words in a String
To count words rather than characters, pass your string to str_word_count().
str_word_count() example
"Hello world!" gives 2, one for each word:
Output: PHP script
<?php
echo str_word_count("Hello world!");
?>
strrev() - Reverse a String
With strrev() you get the same characters back in the opposite order.
strrev() example
Here "Hello world!" comes out backwards:
Output: PHP script
<?php
echo strrev("Hello world!");
?>
strpos() - Search For a Text Within a String
strpos() looks for one piece of text inside another. If it succeeds, it tells you the character position where the first match begins; if it fails, it gives back FALSE.
Tip: Positions are counted from 0, so the very first character is at position 0, not 1.
strpos() example
Looking for "world" in "Hello world!" gives 6, since that word begins at the seventh character:
Output: PHP script
<?php
echo strpos("Hello world!", "world");
?>
str_replace() - Replace Text Within a String
To swap some characters in a string for different ones, use str_replace().
str_replace() example
Here "world" is swapped for "Dolly", turning the greeting into "Hello Dolly!":
Output: PHP script
<?php
echo str_replace("world", "Dolly", "Hello world!");
?>