PHP, lesson 8
PHP was born to produce text, so its standard library is packed with string functions.
Strings are values: functions like strtoupper() return a new string and leave the
original unchanged, so assign the result if you want to keep it.
strpos() returns the position, or false when the text isn't found. Because position 0
is also falsy, always test it with === false, never with a plain if. For yes/no questions
the str_contains family, added in PHP 8, is clearer.
str_replace("old", "new", $text) replaces every occurrence.2 exercises to try what you just read.
strtolower(), strtoupper(), ucfirst() and ucwords() change case.explode(",", $text) splits into an array; implode(", ", $array) joins one back up.str_repeat("-", 20) repeats a string.str_pad("7", 3, "0", STR_PAD_LEFT) pads to a width, giving 007.The functions above count bytes, not letters. That's fine for plain English, but a letter
like é or an emoji takes several bytes in UTF-8. The mb_ functions (mb_strlen(),
mb_substr(), mb_strtoupper()) work with characters instead, so use them for
international text.
printf() prints a format string in which placeholders are replaced by the remaining
arguments; sprintf() does the same but returns the string instead of printing it.
| Placeholder | Meaning |
|---|---|
%s | a string |
%d | an integer |
%.2f | a float with two decimals |
%8.2f | the same, right-aligned in 8 characters |
%-10s | a string left-aligned in 10 characters |
%05d | an integer padded with zeros to 5 digits |
%% | a literal percent sign |
Width and alignment are all you need to line up columns in a table.
The second exercise is a small project combining input (lesson 3), a loop (lesson 5), a function (lesson 6), arrays (lesson 7) and formatting from this lesson. Plan before typing:
A palindrome reads the same forwards and backwards once you ignore case, spaces and
punctuation (keep only letters and digits). Read one line and print yes if it is a
palindrome, otherwise no. An empty line counts as a palindrome. Input is plain ASCII.
Sample input:
Sample output:
Each input line describes one item as name quantity price (the name is one word, the
quantity a whole number, the price a decimal). Print a receipt:
x and the quantity
left-aligned in 4 characters, then the line total right-aligned in 8 characters with two
decimals.TOTAL left-aligned in 15 characters followed by the grand total right-aligned in 8
characters with two decimals.Sample input:
Sample output:
<?php
$name = " ada lovelace ";
$clean = trim($name); // "ada lovelace"
echo ucwords($clean), "\n"; // Ada Lovelace
echo strtoupper($clean), "\n"; // ADA LOVELACE
echo strlen($clean), "\n"; // 12<?php
$word = "Elephant";
echo $word[0], "\n"; // E (zero-based offset)
echo $word[-1], "\n"; // t (negative offsets count from the end)
echo substr($word, 2, 3), "\n"; // eph (start at 2, take 3)
echo strrev($word), "\n"; // tnahpelE<?php
$email = "sam@example.com";
var_dump(str_contains($email, "@")); // bool(true)
var_dump(str_starts_with($email, "sam")); // bool(true)
var_dump(str_ends_with($email, ".org")); // bool(false)
var_dump(strpos($email, "@")); // int(3)<?php
printf("%-8s|%6.2f|\n", "Tea", 3.5); // Tea | 3.50|Never odd or even!yescoffee 2 3.20
bagel 1 2.75coffee x2 6.40
bagel x1 2.75
-----------------------
TOTAL 9.15