Skip to content

PHP Tutorial Strings

Extracting Parts of a String

Lesson 64 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

substr() returns a piece of a string. You give it a start position and, optionally, a length. Positions start at 0.

index.php
PHP
<?php
$word = "Programming";

echo substr($word, 0, 3) . "\n";   // from 0, take 3
echo substr($word, 3) . "\n";      // from 3 to the end
echo substr($word, 3, 4);          // from 3, take 4
Output
OUTPUT
Pro
gramming
gram

Negative numbers count from the end

index.php
PHP
<?php
$file = "photo.jpg";

echo substr($file, -3) . "\n";      // last 3 characters
echo substr($file, 0, -4);          // everything except the last 4
Output
OUTPUT
jpg
photo

Text before and after a character

strstr() returns the text from the first match onwards, or only the part before it if you pass true.

index.php
PHP
<?php
$email = "ravi@example.com";

echo strstr($email, "@") . "\n";          // from @ onwards
echo strstr($email, "@", true) . "\n";    // before @
echo substr(strrchr($email, "."), 1);     // after the last dot
Output
OUTPUT
@example.com
ravi
com

Short text with an ellipsis

index.php
PHP
<?php
$text = "PHP is a popular server-side scripting language";

if (strlen($text) > 20) {
    $text = substr($text, 0, 20) . "...";
}

echo $text;
Output
OUTPUT
PHP is a popular ser...

Cutting in the middle of a word is rarely what you want. For real excerpts, find the last space before the limit.

Single characters

You can read one character with square brackets.

index.php
PHP
<?php
$word = "PHP";

echo $word[0] . "\n";
echo $word[-1];
Output
OUTPUT
P
P

Characters that use several bytes

substr() cuts by bytes, so it can break accented or non-English letters in half. Use mb_substr() for text that may contain them.

index.php
PHP
<?php
$name = "Zoë";

echo mb_substr($name, 0, 3) . "\n";
echo mb_strlen($name);
Output
OUTPUT
Zoë
3

Exercise: get the file extension

Given "archive.tar.gz", print only gz.

Show a possible solution
index.php
PHP
<?php
$file = "archive.tar.gz";

echo substr(strrchr($file, "."), 1);
// or: echo pathinfo($file, PATHINFO_EXTENSION);
Output
OUTPUT
gz