Skip to main content

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:

Prompt
Write a PHP script that uses echo and strlen() to display the length of the string "Hello world!".
Output: PHP script

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:

Prompt
Write a PHP script that uses echo and str_word_count() to display the number of words in the string "Hello world!".
Output: PHP script

strrev() - Reverse a String

With strrev() you get the same characters back in the opposite order.

strrev() example

Here "Hello world!" comes out backwards:

Prompt
Write a PHP script that uses echo and strrev() to reverse and display the string "Hello world!".
Output: PHP script

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:

Prompt
Write a PHP script that uses echo and strpos() to search for the text "world" in the string "Hello world!" and display the position.
Output: PHP script

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!":

Prompt
Write a PHP script that uses echo and str_replace() to replace "world" with "Dolly" in the string "Hello world!" and display the result.
Output: PHP script