PHP & The WebExtra· 25 min read

String Functions

Built-in tools to measure, change and search text.

What you will learn

  • Use common string functions

Built-in string tools

PHP comes with many ready-made functions for working with text (a *string*). You do not have to write these yourself — just call them by name and hand them your text. Here are the ones you will reach for most:

FunctionDoes
strlen($s)Length
strtoupper($s) / strtolower($s)Change case
trim($s)Remove surrounding spaces
str_replace("a","b",$s)Replace text
substr($s, 0, 3)Cut out part
explode(",", $s)Split into an array

You can also chain functions — feed the result of one straight into another. This example first trims the spaces off some messy text, then changes the case or measures the length of the cleaned-up result:

Chaining string functions
<?php
  $text = "  CodingClave  ";
  echo strtoupper(trim($text));   // CODINGCLAVE
  echo strlen(trim($text));        // 11
?>

Read the calls from the inside out. trim($text) runs first and removes the leading and trailing spaces, leaving "CodingClave". That clean text is then passed to strtoupper(...), which makes it all capitals, and on the next line to strlen(...), which counts its 11 letters.

Note: Output (in the browser): CODINGCLAVE11 The two results print side by side: the upper-cased word, then its length. Note strlen counts the trimmed text (11), not the original with spaces — because trim ran first.

Q. Which function removes spaces from the start and end of a string?

Answer: trim() removes leading and trailing whitespace — common when handling form input.

✍️ Practice

  1. Clean and uppercase a messy string.
  2. Split "a,b,c" into an array with explode.

🏠 Homework

  1. Write a function that returns the initials from a full name.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →