Strings

Introduction

Text is everywhere in programs: names, messages, addresses, search words. In PHP, text is a string. PHP has a very large set of string functions, and knowing the common ones saves a lot of work. In this lesson you will join strings, measure them, search inside them, cut parts out and change them. Remember that strings in PHP are not changed in place: a function returns a new string, and you must save or print that result.

How it works

You can write a string in single quotes or in double quotes. Double quotes fill in variables and understand escape codes such as \n (new line) and \t (tab). To put a variable next to other text safely, wrap it in braces: "{$first} {$last}". To join strings, use the dot operator: $first . " " . $last. PHP uses the dot for joining, and the plus sign only for numbers.

The most useful functions are these:

  • strlen($s) counts the characters (bytes) of a string.
  • strtoupper($s) and strtolower($s) change the case; ucfirst and ucwords capitalise the first letter of the text or of each word.
  • trim($s) removes spaces and line breaks from both ends.
  • substr($s, $start, $length) cuts a part out. The first character is at position 0, and a negative start counts from the end.
  • strpos($s, $find) gives the position of the first match, or false if it is missing. Because position 0 is also "falsy", always compare with === false.
  • str_contains, str_starts_with and str_ends_with answer yes or no questions.
  • str_replace($old, $new, $s) replaces every match.
  • str_repeat($s, $times) repeats a string, and str_pad pads it to a width.
  • strrev($s) reverses it, and strcmp($a, $b) compares two strings and gives a number below zero, zero or above zero.

You can read one character with square brackets: $s[0] is the first one. A string can be turned into an array of characters with str_split, and into an array of words with explode(" ", $s). The opposite is implode.

Comparing text uses == or ===. Capital letters matter: "Apple" is not the same as "apple", so use strtolower on both sides if case should not matter.

Example

<?php
$text = "  Learning PHP is fun  ";
$clean = trim($text);
echo "[", $clean, "]\n";
echo strlen($clean), "\n";
echo strtoupper($clean), "\n";
echo strtolower($clean), "\n";
echo ucfirst("hello"), " ", ucwords("hello big world"), "\n";
echo substr($clean, 9, 3), "\n";
echo strpos($clean, "PHP"), "\n";
echo str_replace("fun", "great", $clean), "\n";
echo str_repeat("=", 10), "\n";

$first = "Ada";
$last = "Lovelace";
echo "Full name: {$first} {$last}\n";
echo $first . " " . $last . "\n";
echo strrev("stressed"), "\n";
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";
echo strcmp("apple", "banana") < 0 ? "apple first" : "banana first", "\n";
echo str_contains($clean, "PHP") ? "yes" : "no", "\n";

Line by line

  1. trim removes the two spaces at both ends of the sentence.
  2. strlen counts 19 characters. strtoupper and strtolower change the case.
  3. ucfirst and ucwords capitalise the first letter, and the first letter of each word.
  4. substr($clean, 9, 3) takes three characters starting at position 9, which is PHP.
  5. strpos finds that PHP begins at position 9.
  6. str_replace makes a new string with fun changed to great.
  7. str_repeat draws a line of ten equals signs.
  8. Two ways to join strings: braces in double quotes, and the dot operator.
  9. strrev reverses a word, str_pad adds zeros on the left, strcmp compares, and str_contains answers yes or no.

Expected result

[Learning PHP is fun]
19
LEARNING PHP IS FUN
learning php is fun
Hello Hello Big World
PHP
9
Learning PHP is great
==========
Full name: Ada Lovelace
Ada Lovelace
desserts
007
apple first
yes

In the real world

Every website cleans text: it trims what users type, changes the case before comparing emails, replaces bad characters and builds messages from parts. Search features use strpos and str_contains. Report programs use str_pad and printf to line up columns, and URL tools use explode to split paths into parts.

Common mistakes

  • Using + to join strings. PHP uses the dot, and "a" + "b" is an error.
  • Writing if (strpos($s, "a")) when the match is at position 0. Use !== false.
  • Expecting a function to change the variable. trim($s); alone does nothing; write $s = trim($s);.
  • Forgetting that the first position is 0, so substr($s, 1, 3) starts at the second character.

Best practices

  • Use str_contains for yes or no searches, and strpos only when you need the position.
  • Use trim on every line you read from input.
  • Make text lower case before comparing it when case should not matter.
  • Build long text with printf or implode instead of many dots.

Summary

Strings are joined with the dot operator and written in single or double quotes. Functions such as strlen, trim, substr, strpos, str_replace, str_repeat, str_pad and strtoupper return new strings and never change the original. Positions start at 0, and strpos returns false when nothing is found, so compare it with ===.

Quick check

1. Which operator joins two strings in PHP?
2. What does substr("Learning", 0, 4) return?
3. How should you test that strpos found nothing?
4. What does trim(" hi ") return?

Key takeaways

  • Strings are joined with the dot and positions start at 0.
  • String functions return new strings; they never change the original.
  • strpos returns false when nothing is found, so compare with the strict operator.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.