How to Get Substring from String in PHP
It is possible to get various substrings from a string using the substr() utility in PHP.
In this tutorial, we will learn how to extract any substring we want from a string in PHP using substr().
substr() Syntax
The substr() utility takes three arguments, the string, the start position and the length. The last argument is optional.
substr(string, start, [length])
Get the First Character from a String
To get the first character from a string using substr(), we can set the start position at 0 and the length to 1.
$str = 'text';
$result = substr($str, 0, 1);
dd($result);
t
Exclude First Character from a String
To get the whole string without the first character set the start position of substr() to 1 and don't supply a length.
$str = 'text';
$result = substr($str, 1);
dd($result);
ext
Get the Last Character from a String
To get the last character, pass -1 to substr().
$str = 'hello';
$result = substr($str, -1);
dd($result);
o
A negative start position in substr() will start from the end of a string and a positive start position from the end. Let's have a look at some more examples to get a better understanding of its behaviour.
$str = 'hello';
substr($str, 0, 2); // output: he
substr($str, 0, -2); // output: hel
substr($str, 0); // output: hello
substr($str, -2, 1); // output: l
substr($str, -4); // output: ello
If the start position is greater than the length of the string false will be returned.
$str = 'hello';
$result = substr($str, 6);
dd($result);
false
To avoid this we can dynamically get the length of the string using the strlen() utility.
$str = 'hello';
$result = substr($str, strlen($str) -1);
dd($result);
o
Conclusion
You now know how to get substrings of a string in PHP using the substr() utility.
