The substr() function in PHP is used to extract a portion of a string. This function is often useful when you need to work with a substring within a larger string, such as extracting a part of a sentence or retrieving a fixed number of characters.
// Syntax of PHP substr() function
substr($string, $start, $length);
// Extract substring starting from index 6
<?php
$string = "Hello World";
$substring = substr($string, 6);
echo $substring;
?>
World
// Extract first 5 characters from string
<?php
$string = "Hello World";
$substring = substr($string, 0, 5);
echo $substring;
?>
// Extract last 5 characters using negative index
<?php
$string = "Hello World";
$substring = substr($string, -5);
echo $substring;
?>
// Exclude last 6 characters from the string
<?php
$string = "Hello World";
$substring = substr($string, 0, -6);
echo $substring;
?>
Imagine a text editor that highlights only a specific portion of a sentence. PHP internally performs the same operation using substr() to isolate characters before processing or displaying them.
mb_substr()