substr() returns a piece of a string. You give it a start position and, optionally, a length. Positions start at 0.
<?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
Pro
gramming
gram
Negative numbers count from the end
<?php
$file = "photo.jpg";
echo substr($file, -3) . "\n"; // last 3 characters
echo substr($file, 0, -4); // everything except the last 4
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.
<?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
@example.com
ravi
com
Short text with an ellipsis
<?php
$text = "PHP is a popular server-side scripting language";
if (strlen($text) > 20) {
$text = substr($text, 0, 20) . "...";
}
echo $text;
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.
<?php
$word = "PHP";
echo $word[0] . "\n";
echo $word[-1];
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.
<?php
$name = "Zoë";
echo mb_substr($name, 0, 3) . "\n";
echo mb_strlen($name);
Zoë
3
Exercise: get the file extension
Given "archive.tar.gz", print only gz.
Show a possible solution
<?php
$file = "archive.tar.gz";
echo substr(strrchr($file, "."), 1);
// or: echo pathinfo($file, PATHINFO_EXTENSION);
gz