Chapter 7

Strings and Text Processing

Most of what a program handles is text. Learn to measure it, split it, search it, normalize it, and put it on a page safely.

Chapter 7, Strings and Text Processing

What you will learn

  • Use concatenation, interpolation, and common string functions.
  • Split and join text with explode() and implode().
  • Search and replace text deliberately.
  • Explain why HTML escaping is separate from input validation.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

7.1 Strings as Data

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$word = "café";

echo strlen($word) . PHP_EOL;
echo mb_strlen($word) . PHP_EOL;
echo "[" . trim("   spaced   ") . "]" . PHP_EOL;

7.2 Split, Join, Search, Replace

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$line = "Order 118: two notebooks";

var_dump(str_contains($line, "notebook"));
var_dump(str_contains($line, "Notebook"));
echo str_replace("two", "three", $line) . PHP_EOL;

7.3 Validation and HTML Escaping

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$comment = '<b>Nice & tidy</b>';

if (trim($comment) === "") {
    echo "Comment is required." . PHP_EOL;
}

echo htmlspecialchars($comment, ENT_QUOTES, "UTF-8") . PHP_EOL;

TPRM Lab 7.1: Split and Join Words

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$text = "red,green,blue";
$colors = explode(",", $text);

echo $colors[0] . PHP_EOL;
echo count($colors) . PHP_EOL;
echo implode(" | ", $colors) . PHP_EOL;

TPRM Lab 7.2: Escape Text for HTML

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$name = '<strong>Maya & Co.</strong>';

$safe = htmlspecialchars($name, ENT_QUOTES, "UTF-8");

echo $safe . PHP_EOL;

Back to PHP the TPRM Way