Learn/PHP/8. Strings and a small project
Lesson 8 of 15
Sign in

PHP, lesson 8

Strings and a small project

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.

Pieces of a string

Searching

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.

Changing and splitting

  • str_replace("old", "new", $text) replaces every occurrence.

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

  • 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.
  • A note on multibyte text

    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.

    Formatting with printf

    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.

    PlaceholderMeaning
    %sa string
    %dan integer
    %.2fa float with two decimals
    %8.2fthe same, right-aligned in 8 characters
    %-10sa string left-aligned in 10 characters
    %05dan 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.

    Project: putting it together

    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:

    1. Read lines until the input ends.
    2. Split each line into a name, a quantity and a price.
    3. Compute the line total and add it to a running sum.
    4. Print each row with fixed widths, then the total.

    Further reading

    • String functions
    • sprintf() format reference
    • str_contains()
    • Multibyte string functions

    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:

    • One row per item: the name left-aligned in 10 characters, then x and the quantity left-aligned in 4 characters, then the line total right-aligned in 8 characters with two decimals.
    • Then a line of 23 dashes.
    • Then 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!
    yes
    coffee 2 3.20
    bagel 1 2.75
    coffee    x2       6.40
    bagel     x1       2.75
    -----------------------
    TOTAL              9.15