51: Account for Form Feeds in trim()
Overview
Section titled “Overview”Clean imported text fields with the new default trimming behavior. PHP 8.6 adds the form-feed character to the default set for trim(), ltrim(), and rtrim().
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable trim-form-feed.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/51-trim-form-feed/trim-form-feed.php<?php
declare(strict_types=1);
$value = "\fready\f";echo 'Both: ', bin2hex(trim($value)), PHP_EOL;echo 'Left: ', bin2hex(ltrim($value)), PHP_EOL;echo 'Right: ', bin2hex(rtrim($value)), PHP_EOL;
$oldMask = " \n\r\t\v\0";echo 'Explicit mask: ', bin2hex(trim($value, $oldMask)), PHP_EOL;Expected Result
Section titled “Expected Result”Both: 7265616479Left: 72656164790cRight: 0c7265616479Explicit mask: 0c72656164790cWhy It Works
Section titled “Why It Works”The change applies when you omit the character mask. Pass an explicit mask for a format that uses form feeds as edge delimiters. The sample prints hexadecimal so the invisible bytes are easy to compare.
Exercise
Section titled “Exercise”Trim a form feed from only the left side and verify that the hexadecimal output still ends in 0c.
Wrap-up
Section titled “Wrap-up”Continue with Handle Stream Flush and Close Failures.