String padding, trimming, wrapping: str_pad, trim, wordwrap
Concept
PHP's string padding, trimming, and wrapping functions handle common text-normalization and display tasks. These are byte-string functions — use mb_* equivalents for multi-byte text (PHP 8.3+ adds mb_str_pad).
trim($str, $characters) removes leading and trailing characters. Default character mask is " \t\n\r\0\x0B" (space, tab, newlines, null, vertical tab). ltrim trims left only, rtrim (alias chop) trims right only. The $characters parameter specifies the exact set to remove — ranges work: "0..9" trims any digit. A common gotcha: trim with a custom mask is NOT a substring removal — it removes any combination of those characters from the ends.
str_pad($input, $length, $pad_string, $pad_type) pads a string to a minimum length. STR_PAD_RIGHT (default), STR_PAD_LEFT, STR_PAD_BOTH. $pad_string can be multiple characters — it cycles if needed. If the input is already at or beyond $length, str_pad returns it unchanged.
wordwrap($string, $width, $break, $cut_long_words) wraps text at word boundaries. $break is the line-break string (default "\n"). $cut_long_words set to true forces a hard break in the middle of words longer than $width. Used for email body formatting or terminal output.
chunk_split($string, $chunklen, $end) inserts $end after every $chunklen characters. Classic use: formatting PEM certificates (base64 with \n every 64 characters) or credit card display (1234-5678-9012-3456).
Code Example
<?php
declare(strict_types=1);
// trim — clean user input
$input = " \t Hello, World! \n ";
echo trim($input); // "Hello, World!"
// Custom character mask
$path = '///path/to/file///';
echo trim($path, '/'); // "path/to/file"
// Trim digits and spaces from ends
$messyId = '00042 ';
echo ltrim($messyId, '0 '); // "42 " — only left side
// str_pad — table formatting
$headers = ['Product', 'Qty', 'Price'];
foreach ($headers as $h) {
echo str_pad($h, 12);
}
echo "\n";
// "Product Qty Price "
// Zero-pad numbers (use sprintf for numeric formatting though)
for ($i = 1; $i <= 5; $i++) {
echo str_pad($i, 3, '0', STR_PAD_LEFT) . "\n";
}
// "001", "002", "003"...
// Center a title
function centerText(string $text, int $width): string
{
return str_pad($text, $width, ' ', STR_PAD_BOTH);
}
echo centerText('PHP 8.4', 20); // " PHP 8.4 "
// wordwrap — email/terminal formatting
$longText = 'This is a very long string that should be wrapped at a reasonable column width for display purposes.';
echo wordwrap($longText, 40, "\n", true);
// Wraps at word boundaries, hard-breaks words > 40 chars
// chunk_split — PEM cert formatting, credit card display
$base64 = base64_encode('some binary data for certificate use');
$pem = chunk_split($base64, 64, "\n"); // PEM line length
$card = '4111111111111111';
echo chunk_split($card, 4, '-'); // "4111-1111-1111-1111-"
// Note: chunk_split always adds $end after the last chunk too
echo rtrim(chunk_split($card, 4, '-'), '-'); // "4111-1111-1111-1111"