String Functions

Course 1 · Ch 7
Strings: Functions, Formatting, and Manipulation
The built-in toolkit for measuring, searching, slicing, and reshaping text

Strings have appeared in every chapter so far, but always as fixed pieces of text. This chapter covers PHP's large built-in library of string functions — the everyday tools for working with text that isn't already in exactly the shape you need.

Length and Case

<?php $text = "Hello, PHP!"; echo strlen($text); // 11 — number of characters echo strtoupper($text); // "HELLO, PHP!" echo strtolower($text); // "hello, php!" echo ucfirst("hello"); // "Hello" — capitalises only the first letter echo ucwords("hello there"); // "Hello There" — capitalises every word ?>

Searching Inside a String

<?php $sentence = "The quick brown fox"; var_dump(str_contains($sentence, "brown")); // true echo strpos($sentence, "brown"); // 10 — the starting position, or false if not found var_dump(str_starts_with($sentence, "The")); // true ?>
strpos can return 0 — and 0 is "falsy", so use === for the not-found check
If the search text is found right at the very start of the string, strpos() correctly returns 0. But 0 behaves as "false-ish" in a loose boolean check, making if (!strpos(...)) wrongly treat "found at position 0" the same as "not found at all". Always write strpos($str, $search) === false to test specifically for "not found", never a plain truthy/falsy check.

Slicing and Replacing

<?php $text = "Hello, World!"; echo substr($text, 7); // "World!" — from position 7 to the end echo substr($text, 7, 5); // "World" — 5 characters starting at position 7 echo str_replace("World", "PHP", $text); // "Hello, PHP!" echo trim(" padded text "); // "padded text" — removes leading/trailing whitespace ?>

Splitting and Joining

<?php $csv = "apple,banana,cherry"; $parts = explode(",", $csv); // ["apple", "banana", "cherry"] print_r($parts); $joined = implode(" - ", $parts); // "apple - banana - cherry" echo $joined; ?>

explode() turns a string into an array by splitting on a delimiter; implode() does the reverse — joining an array's elements into a single string with a chosen separator between them.

Formatting Output — sprintf

<?php $price = 9.5; $formatted = sprintf("Price: £%.2f", $price); echo $formatted; // "Price: £9.50" — forces exactly 2 decimal places $name = "Sam"; $age = 7; echo sprintf("%s is %d years old", $name, $age); // "Sam is 7 years old" ?>

sprintf() builds a formatted string using placeholders — %s for strings, %d for integers, %.2f for a float fixed to 2 decimal places. It's especially useful for money values, where plain string interpolation can't reliably guarantee a consistent number of decimal places.

FunctionWhat it does
strlen($s)Length in characters
strtoupper / strtolowerChange case
str_contains / strposSearch inside a string
substr($s, $start, $len)Extract part of a string
str_replace($search, $replace, $s)Replace occurrences
trim($s)Remove leading/trailing whitespace
explode($delim, $s)String → array
implode($glue, $arr)Array → string
sprintf($format, ...)Build a precisely formatted string
Single quotes vs double quotes also matters for strlen() with special characters — but for everyday text, the function library above works the same regardless of quote style
Most of the time it doesn't matter whether the original string used single or double quotes — once it's stored in a variable, functions like strlen() or strtoupper() treat it identically either way.

Coding Challenges

Challenge 1

Take the string " philip osztromok " (note the extra spaces). Trim it, then use ucwords() to capitalise each word properly, and echo the final cleaned-up result along with its length using strlen().

📄 View solution
Challenge 2

Given the string "2026-06-20", use explode() to split it into year, month, and day parts. Then use sprintf() to echo it back out in the format "20/06/2026" (day/month/year, UK style).

📄 View solution
Challenge 3

Write a function censorWord($sentence, $word) that uses str_replace() to replace every occurrence of $word in $sentence with asterisks matching its length (e.g. "cat" becomes "***"). Test it on a sentence containing the target word twice.

📄 View solution

Chapter 7 Quick Reference

  • strlen, strtoupper/strtolower, ucfirst, ucwords — length and case
  • str_contains, strpos, str_starts_with — searching; use === false to test "not found" with strpos
  • substr($s, $start, $len) — extract a portion of a string
  • str_replace, trim — replacing and cleaning up whitespace
  • explode / implode — string ↔ array conversions
  • sprintf($format, ...) — precise formatted output, especially for numbers/money
  • Next chapter: superglobals — $_GET, $_POST, and $_SERVER, and handling form input