CodeBlanks Logo Icon CodeBlanks

Slicing with substr()

PHP course · Beginner · Lesson 89/116

Learn to take a portion of a string with substr().

Slicing with substr()

To take only a portion of a string, use substr(). It is called as substr($string, $start, $length); $start is the starting position, $length is the number of characters to take. It returns a new string and does not change the original.

Example: substr('Hello', 0, 3) returns 'Hel'. Positions start at zero, so the first character is at position 0.

Negative start

When $start is negative, PHP counts from the end of the string. substr('Hello', -3) takes the last three characters: 'llo'. This is handy when you want a slice from the end without knowing the length.

Length can also be negative: substr('Hello', 0, -2) gives everything except the last two characters: 'Hel'. Negative values make string handling flexible.

When length is omitted

The $length argument is optional. When it is omitted, substr() takes everything from the starting position to the end of the string. substr('Hello', 3) returns 'lo'.

This is handy for skipping a prefix. For example, to drop the first four characters of a file name, substr($name, 4) is enough. Combined with a negative start, you can make very flexible slices.

Exercise Mask all but the last four digits

Assign "4111-2222-3333-4444" to $card. Use substr() with a negative start to assign the last four digits to $last. Then in a single echo join "****-****-****-" and $last with the . operator.

Show example solution
First assign $card, then $last = substr($card, -4); then add echo "****-****-****-" . $last;
Example solution:
<?php
$card = "4111-2222-3333-4444";
$last = substr($card, -4);
echo "****-****-****-" . $last;

Test yourself

  1. What does substr('Telephone', 0, 3) return?

    substr('Telephone', 0, 3)
    • lephone
    • eph
    • Tel
    • T
    Show answer

    Tel — Correct. Position 0, length 3 gives 'Tel'.

  2. Take the last four characters

    $code = 'TR2025';
    $suffix = substr($code, ____);
    echo $suffix;
    Show answer
    $code = 'TR2025';
    $suffix = substr($code, -4);
    echo $suffix;
  3. What does substr('Hello', -3) return?

    substr('Hello', -3)
    • Hel
    • ello
    • ell
    • llo
    Show answer

    llo — Correct. -3 takes the last three characters: 'llo'.

All lessons in Beginner