What is the substr() function in PHP?

There are several functions in PHP that are used to manipulate strings in PHP. One such function is the substr() function.

substr() is a string manipulation function that will return a substring from the string that was passed based on other parameters of the function that was passed.

Syntax

substr($string,$offset,$length)

Parameter

This function requires three parameters.

  • The first parameter is the string input from which the subtring is to be extracted.

  • The offset parameter is the second parameter. It indicates the position from which the substring is to start. It is an integer v value.

    • If The offset is negative, the substring will be formed starting from the end of the string to end at the offset’th position when counting from zero.

    • If offset is non-negative, the start of the substring will be the beginning of the string to the offset’th position when counting from zero.

    • If the offset is greater than the length of the input string, the substring to be returned will be empty.

  • The length parameter is more or less optional and indicates the length of the substring to be returned after the offset has been set.

    • If length is negative, that amount of strings will be removed from the input string.

    • If the length is positive, that length of string will be returned (at most).

Code

<?php
$j = 'geography';
//Last 3 strings are cutoff and the count
//starts from the fourth string counting from end 'Y'
//output:"a"
$junet = substr($j,-4, -3);
//this returns the string from the eight position
//output:"hy"
$ju = substr($j,7);
//Last 3 strings are cutoff and the count starts from
//the fourth string counting from beginnig 'g'
//output:"ra"
$jun = substr($j,4,-3);
//starts from the end of the string till the 3rd string
//output:phy
$june = substr($j,-3);
//starts the substring from the 6th position
//Output: aphy
$juneth = substr($j,5,5);
echo $junet."\n";
echo $ju ."\n";
echo $jun ."\n";
echo $june."\n";
echo $juneth."\n";
?>

Explanation

The comments attached to the code provide a very detailed explanation of what the code does. However, to summarize, the substr() function will you get the set of strings that you would wish to get from a string input. All you need to do is provide the string input and the offset length, and you are good to go.