0Pricing
PHP Academy · Lesson

Substring and Padding Functions

Extract and format string segments with substr, str_pad, and wordwrap.

Substring and Padding Functions is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Extracting Parts of Strings

PHP has powerful functions to extract, truncate, and pad strings. These are essential for formatting output and processing text data.

substr()

Extract a portion of a string by start position and optional length:

<?php
$str = 'Hello, World!';

echo substr($str, 7);        // World!
echo substr($str, 7, 5);    // World
echo substr($str, -6);      // World!
echo substr($str, -6, 5);   // World

mb_substr()

For multi-byte strings (UTF-8), use mb_substr() to extract correctly:

<?php
$str = 'Привет Мир'; // Russian

// substr counts bytes, not characters:
echo strlen($str);      // 19 bytes

// mb_substr counts characters:
echo mb_substr($str, 0, 6); // Привет

str_pad()

Pad a string to a given length:

<?php
// Default: right-pad with spaces
echo str_pad('5', 3, '0', STR_PAD_LEFT);   // 005
echo str_pad('PHP', 10);                    // 'PHP       '
echo str_pad('hi', 8, '-', STR_PAD_BOTH);  // ---hi---

// Format invoice numbers:
echo 'INV-' . str_pad(42, 5, '0', STR_PAD_LEFT); // INV-00042

wordwrap()

Wrap a string at a specified width, breaking at word boundaries:

<?php
$text = 'The quick brown fox jumped over the lazy dog';

echo wordwrap($text, 15, PHP_EOL, false);
// The quick brown
// fox jumped over
// the lazy dog

chunk_split()

Insert a separator string every N characters — useful for encoding output like base64:

<?php
$data = '1234567890ABCDEF';

echo chunk_split($data, 4, '-');
// 1234-5678-90AB-CDEF-

// Typical use: base64 encoded email attachments
$encoded = base64_encode(file_get_contents('file.bin'));
$formatted = chunk_split($encoded, 76, "\n");

nl2br()

Convert newlines to HTML <br> tags for browser display:

<?php
$text = "Line one\nLine two\nLine three";

echo nl2br($text);
// Line one<br />\nLine two<br />\nLine three

sprintf() for Formatted Strings

sprintf() formats a string with placeholders — great for generating structured output:

<?php
$name  = 'Alice';
$score = 95.5;
$rank  = 1;

$line = sprintf('%-10s %6.2f%%  #%d', $name, $score, $rank);
echo $line;
// Alice       95.50%  #1

number_format()

Format numbers as strings with thousands separators and decimal points:

<?php
$amount = 1234567.891;

echo number_format($amount);                   // 1,234,568
echo number_format($amount, 2);               // 1,234,567.89
echo number_format($amount, 2, ',', '.');     // 1.234.567,89 (European)
echo number_format($amount, 2, '.', '');      // 1234567.89 (no separator)

String Truncation with Ellipsis

Safely truncate long text with an ellipsis for display:

<?php
function truncate(string $text, int $max, string $suffix = '...'): string {
    if (mb_strlen($text) <= $max) return $text;
    return mb_substr($text, 0, $max - mb_strlen($suffix)) . $suffix;
}

echo truncate('The quick brown fox', 15);
// The quick br...

String Reversal

Reverse a string with strrev() (bytes, not multi-byte aware):

<?php
echo strrev('Hello');  // olleH
echo strrev('12345');  // 54321

// Palindrome check
function isPalindrome(string $s): bool {
    $s = strtolower(preg_replace('/[^a-zA-Z]/', '', $s));
    return $s === strrev($s);
}

var_dump(isPalindrome('racecar'));  // true
var_dump(isPalindrome('PHP'));      // false

String Repeat and Fill

Build repeated string patterns for formatting or padding:

<?php
// Build a progress bar
function progressBar(int $percent, int $width = 20): string {
    $filled = (int) round($percent / 100 * $width);
    $empty  = $width - $filled;
    return '[' . str_repeat('#', $filled) . str_repeat('-', $empty) . "] $percent%";
}

echo progressBar(65);  // [#############-------] 65%

Quick Check

Which function inserts a separator character every N characters in a string?

Recap: Substring and Padding

Key functions:

  • substr($str, start, length) — extract by position
  • mb_substr() — multi-byte safe extraction
  • str_pad() — pad to desired length
  • wordwrap() — wrap at word boundaries
  • chunk_split() — insert delimiter every N chars
  • sprintf() — formatted string building

Frequently asked questions

Is the “Substring and Padding Functions” lesson free?

Yes — the full text of “Substring and Padding Functions” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Substring and Padding Functions”?

Extract and format string segments with substr, str_pad, and wordwrap. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Substring and Padding Functions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. String Basics and Concatenation
  2. Searching and Replacing in Strings
  3. Substring and Padding Functions
  4. Splitting and Joining Strings
← Back to PHP Academy