Splitting, Joining and Formatting Strings

4.Splitting, Joining and Formatting Strings

M

In this chapter

We'll learn how to split a string into pieces with explode() and str_split(), join pieces with implode(), and format text and numbers with sprintf(), printf(), number_format() and str_pad() — to turn "Haircut;Hot towel" and 27.5 into "haircut and hot towel, £27.50".

14–16 min

The Problem in Real Life

Olivia wants two changes to the reminder. A booking stores its services in one field, separated by semicolons, and the reminder prints that field as it is: "your Haircut;Hot towel". She wants "your haircut and hot towel".

Then the price. A haircut with a hot towel costs £27.50, but the reminder says "Total: £27.5". A plain haircut says "Total: £25".

O

£27.5 looks like a typo. Prices always have two decimals: £27.50, £25.00.

Olivia

Raw Values vs. Formatted Text

Splitting and joining

One field with semicolons has to become a list, and a list has to become a sentence.

Numbers that look right

27.5 has to show as £27.50, and 9 as 09. Printing a number as it is isn't enough.

Lining things up

Tom's printed day list needs columns that line up, whatever the length of each name.

Splitting, Joining and Formatting Strings

From raw values to a finished message: good text needs two more skills: taking a string apart, and giving values exactly the right shape. This chapter covers both:

  • Splitting: explode() and str_split() turn one string into an array of pieces.
  • Joining: implode() turns an array into one string.
  • Formatting: sprintf(), printf(), number_format() and str_pad() control how numbers and text look.

explode: explode($separator, $string) splits a string wherever the separator appears and gives back an array of the pieces. (You met arrays in Act 06; Act 08 covers them fully.) explode(";", "Haircut;Hot towel") gives ["Haircut", "Hot towel"]. A third argument limits the number of pieces, and the last piece then keeps the rest of the string: explode(" ", "15:00 Haircut and hot towel", 2) gives the time, and then everything after the first space. If the separator isn't in the string at all, you get an array with one item, the whole string.

explode() splits a string into an array
<?php
$stored = "Haircut;Hot towel";
$services = explode(";", $stored); // ["Haircut", "Hot towel"]
echo count($services), " services\n"; // 2 services
echo $services[0], "\n"; // Haircut
$line = "15:00 Haircut and hot towel";
$pieces = explode(" ", $line, 2); // at most 2 pieces
echo $pieces[0], " | ", $pieces[1], "\n";
// 15:00 | Haircut and hot towel
echo count(explode(";", "Haircut")), "\n"; // 1: no separator, so one piece

str_split: str_split($string, $length) cuts a string into pieces of a fixed length instead: str_split("900123", 3) gives ["900", "123"]. Like everything in chapters 3 and 4, it counts bytes. To look inside an array while you learn, print_r() prints its items in a readable way.

str_split() cuts into equal pieces
<?php
print_r(str_split("900123", 3));
// Array
// (
// [0] => 900
// [1] => 123
// )

implode: implode($separator, $array) is the opposite of explode(). It joins every item of an array into one string, with the separator between the items — never after the last one. implode(" and ", ["Haircut", "Hot towel"]) gives Haircut and Hot towel. It's the easiest way to avoid a comma at the end or a missing space.

implode() joins an array into a string
<?php
$services = explode(";", "Haircut;Hot towel");
echo implode(" and ", $services), "\n"; // Haircut and Hot towel
echo strtolower(implode(" and ", $services)), "\n"; // haircut and hot towel
echo implode(", ", ["Haircut", "Beard trim", "Hot towel"]), "\n";
// Haircut, Beard trim, Hot towel — no comma after the last item
$digits = "07700900123";
echo substr($digits, 0, 5), " ", implode(" ", str_split(substr($digits, 5), 3)), "\n";
// 07700 900 123

sprintf: sprintf($format, ...$values) builds a string from a format string: a template with placeholders that start with %. Each placeholder takes the next value and gives it a shape. %s puts in a string, %d a whole number, and %.2f a number with exactly two decimals, rounded. So sprintf("Total: £%.2f", 27.5) gives Total: £27.50. Between the % and the letter you can add a width: %02d means "at least two digits, filled with zeros", so sprintf("%02d:%02d", 9, 0) gives 09:00. That's the pattern Act 06 used for slot times. %% prints a real percent sign, and %1$s takes the first value again; write that one in single quotes, or PHP reads $s as a variable. The table below lists the common placeholders.

Table — Common sprintf() placeholders
PlaceholderMeansExample and result
%sA stringsprintf("Hi %s", "Clare") gives Hi Clare
%dA whole numbersprintf("%d slots", 16) gives 16 slots
%.2fA number with 2 decimals, roundedsprintf("£%.2f", 27.5) gives £27.50
%02dAt least 2 digits, filled with 0sprintf("%02d:%02d", 9, 0) gives 09:00
%5dAt least 5 wide, padded on the leftsprintf("[%5d]", 42) gives [ 42]
%-6sAt least 6 wide, padded on the rightsprintf("[%-6s]", "Ben") gives [Ben ]
%%A percent signsprintf("%d%% off", 10) gives 10% off
%1$sThe first value (again)sprintf('%1$s, %1$s!', "Hi") gives Hi, Hi!
sprintf() gives every value its shape
<?php
$services = "haircut and hot towel";
$total = 27.5;
$message = sprintf("Your %s. Total: £%.2f.", $services, $total);
echo $message, "\n"; // Your haircut and hot towel. Total: £27.50.
echo sprintf("£%.2f", 25), "\n"; // £25.00
echo sprintf("£%.2f", 9.999), "\n"; // £10.00: rounded
echo sprintf("%02d:%02d", 9, 0), "\n"; // 09:00
echo sprintf("[%5d] [%-6s] [%6s]", 42, "Ben", "Ben"), "\n"; // [ 42] [Ben ] [ Ben]
echo sprintf("%d%% off", 10), "\n"; // 10% off
echo sprintf('%2$s: %1$s', "Haircut", "15:00"), "\n"; // 15:00: Haircut

printf: printf() works exactly like sprintf(), but it prints the result instead of giving it back, and returns the number of bytes it printed. Use sprintf() when you need the text in a variable — for a message you're going to send — and printf() to print straight away.

printf() prints straight away
<?php
$bytes = printf("%d slots left\n", 3); // prints the line...
echo $bytes, "\n"; // ...and returns its length: 13
// 3 slots left
// 13

number_format: number_format($number, $decimals) formats a number for people to read: number_format(1234.5, 2) gives 1,234.50, with a comma between the thousands. Two more arguments change the decimal point and the thousands separator, for countries that write 1.234,50. Use it for amounts you show; use sprintf() when the number is part of a fixed pattern.

number_format() for amounts people read
<?php
echo number_format(1234.5, 2), "\n"; // 1,234.50
echo number_format(1234.5), "\n"; // 1,235: no decimals, rounded
echo number_format(1234.5, 2, ",", "."), "\n"; // 1.234,50
echo "£" . number_format(27.5, 2), "\n"; // £27.50

str_pad: str_pad($string, $length, $padding, $side) makes a string at least $length long by adding a padding character, by default spaces on the right. STR_PAD_LEFT pads on the left, which lines up numbers by their last digit. That's how Tom's printed day list gets straight columns. sprintf() can pad too: %-10s pads a string to 10 on the right. Both count bytes, so a name with an é ends up one space short. Chapter 6 shows the fix, mb_str_pad().

str_pad() lines up Tom's day list
<?php
$bookings = [
["09:00", "Daniel Brooks", 25],
["09:30", "Ann Lee", 27.5],
["10:00", "Sam Ortiz", 10],
];
foreach ($bookings as $booking) {
echo $booking[0], " ",
str_pad($booking[1], 15, "."),
str_pad(number_format($booking[2], 2), 8, " ", STR_PAD_LEFT), "\n";
}
// 09:00 Daniel Brooks.. 25.00
// 09:30 Ann Lee........ 27.50
// 10:00 Sam Ortiz...... 10.00

Key Takeaway

explode() splits a string into an array at a separator; implode() joins an array into a string, with the separator only between items. sprintf() fills a format string — %s for text, %d for whole numbers, %.2f for two decimals, %02d for zero-padding — and returns it; printf() prints it. number_format() adds thousands separators, and str_pad() pads text to a width.

Why This Matters

Customers judge a business by its messages. "£27.5" looks like a mistake and "Haircut;Hot towel" looks like a machine; "your haircut and hot towel, £27.50" looks like Tom wrote it. sprintf() and number_format() are how every price, time and total gets its proper shape.

And explode() and implode() are the bridge between text and lists. You'll use them all the time: to read a line from a file (Act 15), to list services, or to take a code apart.

The reminder now reads "your haircut and hot towel tomorrow at 15:00. Total: £27.50." Then, testing the customer lookup, Mia finds something worrying. She types Tom's number without the first zero, "7700900123", and the screen shows Tom's bookings anyway. Two different strings, and PHP says they're equal. That's the next chapter: comparing strings.