Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 147 ยท Strings in Depth

String Functions

A practical guide to PHP string functions - strlen, str_contains, strpos, substr, str_replace, trim, case changes, str_pad, str_repeat, strrev, wordwrap and nl2br.

Most of what a web application does is string work: cleaning up form input, building URLs and slugs, searching text, shortening previews, formatting names, and producing HTML. PHP has a huge library of string functions for these jobs, and knowing the core twenty or so makes you dramatically faster.

This lesson is a tour of the functions you'll use every day, grouped by task: measuring, searching, extracting, replacing, trimming, changing case, padding and repeating, and wrapping text. For each one you'll see the behavior that trips people up, such as negative offsets, the 0 position trap, and what trimming actually removes. You should know string basics (quotes, interpolation, concatenation) from Strings.

The functions in this lesson work on bytes. That's perfect for ASCII text like English words, URLs, codes and identifiers. For text with accented letters, other scripts or emoji, some of them give wrong results, and you'll need the mb_* versions from Unicode and Multibyte Strings.

Measuring: strlen, substr_count, str_word_count

strlen() returns a string's length in bytes. substr_count() counts how often a substring occurs, and str_word_count() counts words (ASCII letters only):

PHP Measuring strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This prints 67, 3, 15, 0, then the validation message. substr_count is case-sensitive and doesn't count overlapping matches: substr_count('aaa', 'aa') is 1.

Searching: str_contains, str_starts_with, str_ends_with

For yes/no questions, PHP 8.0 added three clear, bool-returning functions. They're case-sensitive, and an empty needle always matches.

PHP Asking yes/no questions about a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The results are true, true, false, true, and the image list is photo.JPG, scan.jpeg. Before PHP 8 you'd write strpos($url, '/blog/') !== false; you'll still see that in older code.

Finding positions: strpos and friends

When you need where something is, use the position functions. Positions start at 0, and they return false when nothing is found:

Function Finds
strpos($haystack, $needle, $offset = 0) first occurrence
stripos(...) first occurrence, case-insensitive
strrpos(...) last occurrence
strripos(...) last occurrence, case-insensitive
strstr($haystack, $needle, $before = false) the rest of the string from the first match
strrchr($haystack, $char) the rest from the last occurrence of a character
PHP Finding where text appears

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The positions are int(7), int(15), bool(false) and int(16), the extension is jpg, and the strstr lines print @example.org and grace.

A match at the very start returns 0, which is falsy. Never write if (strpos($s, 'x')); compare with !== false, or use str_contains() when you only need yes or no. The Using Built-in Functions lesson shows this trap in action.

For real file paths, pathinfo($path, PATHINFO_EXTENSION) is the purpose-built tool, and Regular Expressions handle complex searches.

Extracting: substr

substr($string, $offset, $length = null) cuts out part of a string. Both arguments can be negative: a negative offset counts from the end, and a negative length stops that many characters before the end.

PHP Cutting strings with substr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is INV, 2026, 00042, 2026, |, I2, then the preview Functions make code reusable,.... Since PHP 8.0, substr returns an empty string (not false) when the offset is past the end.

Replacing: str_replace

str_replace($search, $replace, $subject) replaces every occurrence and returns the new string. Each argument can be an array, which lets you do many replacements in one call. str_ireplace ignores case.

PHP Replacing text with str_replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
Hello Ana, your order #1042 ships on Monday.
dog, Cat, dogalog (2 replaced)
dog, dog, dogalog
cc
2026-12-09

Two lessons hide in there. First, str_replace matches inside words, so catalog became dogalog; use preg_replace with word boundaries (/\bcat\b/) when that matters. Second, with arrays, each pair runs on the result of the previous one: a became b, then both bs became c. When you need simultaneous replacements, use strtr($text, ['a' => 'b', 'b' => 'c']), which gives bc and never replaces text it already replaced.

Trimming: trim, ltrim, rtrim

trim() removes whitespace from both ends; ltrim() and rtrim() work on one side. By default "whitespace" means space, tab, newline, carriage return, NUL byte and vertical tab. A second argument replaces that list with your own characters (not a substring), and a..z style ranges are allowed:

PHP Trimming whitespace and characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output starts with string(17) "[email protected]", then 1.5, path/to/folder, 42 and Title. The last line prints pa, not path: rtrim keeps removing any of the characters ., h, t, m, l from the end, so it eats the h and t of path too. To remove a suffix, use str_ends_with() with substr().

Trim every text field from a form before validating it. Users paste values with stray spaces and newlines more often than you'd think. See Form Validation.

Changing case

Function Result for 'hello wORLD'
strtoupper HELLO WORLD
strtolower hello world
ucfirst Hello wORLD (only the first character)
lcfirst hello wORLD
ucwords Hello WORLD (first letter of each word)

These are ASCII-only since PHP 8.2: they never depend on the system locale and leave non-ASCII bytes alone, so strtoupper('cafรฉ') gives CAFรฉ. Use mb_strtoupper() for international text.

PHP Changing case, names and titles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is Php, Mary-ann O'neil, Mary-Ann O'Neil, then bool(false), bool(true), bool(true), and finally first_name_here. The second argument of ucwords lists the characters that start a new word. strcasecmp() compares two strings ignoring case and returns 0 when they're equal.

Padding and repeating: str_pad, str_repeat

str_pad($string, $length, $padString = ' ', $padType = STR_PAD_RIGHT) extends a string to a minimum length. It never shortens. str_repeat() repeats a string:

PHP Padding, repeating and simple tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
007
Total.......$9.99
[***center***]
too long already
=-=-=-=-=-=-=-=-=-=-
Apples        3
Kiwis        12
Mangoes     140

For anything beyond simple columns, sprintf('%-10s%5d', ...) is more flexible; see Formatting Strings.

Reversing, splitting and wrapping

A few more functions round out the toolkit:

  • strrev($s) reverses a string (byte by byte).
  • str_split($s, $length = 1) splits into chunks of a fixed length.
  • wordwrap($s, $width = 75, $break = "\n", $cut = false) breaks long text into lines at spaces. With $cut = true, it also splits words longer than the width.
  • nl2br($s) inserts <br /> before every newline, for showing multi-line text in HTML.
  • explode() and implode() split on and join with a separator; they get full coverage in Formatting Strings.
PHP strrev, str_split, wordwrap and nl2br

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

strrev('stressed') gives desserts, and the card number prints as 4111 2222 3333 4444. wordwrap breaks the sentence into lines of at most 30 characters, and with $cut = true it chops the long word into Supercal, ifragili and stic. The last line is HTML source (on a web page the browser would render the line break):

TEXT
First line &lt;b&gt;bold?&lt;/b&gt;<br />
Second line

Note the order: escape with htmlspecialchars() first, then nl2br(). The other way around, the <br /> tags themselves would be escaped into visible text. Escaping is covered in depth in Preventing XSS.

Putting it together: a slug function

A slug is the URL-friendly version of a title, like php-string-functions. Building one uses several functions from this lesson:

PHP Building URL slugs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The slugs are php-string-functions-a-practical-guide, tips-and-tricks-for-c-plus-plus, untitled and a-very-long-title-th. One regular expression collapses every run of other characters into a single dash; you'll learn how that pattern works in Regular Expressions. For titles in other languages, you'd first transliterate accented letters, which needs the multibyte tools of the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does substr('database', -4) return?

    A negative offset counts from the end, so -4 starts at the fourth-last character and takes the rest.
  2. 2. What does str_replace(['a', 'b'], ['b', 'c'], 'ab') return?

    The pairs run one after another. First 'ab' becomes 'bb', then both b's become c. strtr() would give 'bc'.
  3. 3. What does rtrim('report.txt', '.txt') return?

    The second argument is a set of characters, not a suffix. rtrim keeps removing t, x and . from the end, so it also removes the last t of report.
  4. 4. Which function returns a plain true or false for whether a string contains a substring?

    str_contains (PHP 8.0) returns a bool. strpos returns a position or false, strstr returns part of the string, and substr_count returns a number.
  5. 5. Why should you call htmlspecialchars before nl2br, not after?

    htmlspecialchars escapes every < and >, including the ones nl2br added. Escape the user's text first, then add the line breaks.

Summary

  • strlen measures bytes; substr_count and str_word_count count occurrences and words.
  • str_contains, str_starts_with and str_ends_with (8.0) answer yes/no questions. strpos/stripos/strrpos return positions or false: always compare with !== false.
  • substr extracts by position, with negative offsets and lengths counting from the end.
  • str_replace replaces every occurrence (arrays allowed, results chain); strtr replaces simultaneously; substr_replace replaces by position.
  • trim, ltrim and rtrim remove whitespace, or a set of characters you specify.
  • strtoupper, strtolower, ucfirst and ucwords change case (ASCII only); str_pad and str_repeat build fixed-width output.
  • strrev, str_split, wordwrap and nl2br reverse, chunk and wrap text. Escape with htmlspecialchars before nl2br.
  • All of these work on bytes. Use mb_* functions for non-ASCII text.

Next: Unicode and Multibyte Strings