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)andstrtolower($s)change the case;ucfirstanducwordscapitalise 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, orfalseif it is missing. Because position 0 is also "falsy", always compare with=== false.str_contains,str_starts_withandstr_ends_withanswer yes or no questions.str_replace($old, $new, $s)replaces every match.str_repeat($s, $times)repeats a string, andstr_padpads it to a width.strrev($s)reverses it, andstrcmp($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
trimremoves the two spaces at both ends of the sentence.strlencounts 19 characters.strtoupperandstrtolowerchange the case.ucfirstanducwordscapitalise the first letter, and the first letter of each word.substr($clean, 9, 3)takes three characters starting at position 9, which isPHP.strposfinds thatPHPbegins at position 9.str_replacemakes a new string withfunchanged togreat.str_repeatdraws a line of ten equals signs.- Two ways to join strings: braces in double quotes, and the dot operator.
strrevreverses a word,str_padadds zeros on the left,strcmpcompares, andstr_containsanswers 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_containsfor yes or no searches, andstrposonly when you need the position. - Use
trimon every line you read from input. - Make text lower case before comparing it when case should not matter.
- Build long text with
printforimplodeinstead 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
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.