Introduction
In this article I will explain the string Substr() function in PHP. This function returns parts of the string starting at a specified position.
Syntax
substr('str_name', start_pos); |
Parameter |
Description |
string_name |
Pass the string name or string |
start_pos |
Refers to the position of the string to be cut |
In the parameter the input string must be one character or longer and the "substr()" function returns the portion of the string specified by the start position and length parameter.
Using a Negative Start
If the starting position is non-negative then the returned string will start at the start the position in the string and the index counts from zero. Such as in the string Ram, the character R is at index zero and space is at index three.
Example
<?php
$a = "MCN Sulotion";
$b = "Ram Kumar";
$c = "Shyam Kumar";
echo substr("$a",-1)."<br>";
echo substr("$b",-2)."<br>";
echo substr("$c",-3,1)."<br>";
?>
Output
Using a Negative Length
If the specified length is positive then the string returned will contain at most length characters beginning from start (depending on the string length). If the length is zero, then an empty string will be returned zero or false.
Example
<?php
$a = "MCN Sulotion";
$b = "Ram Kumar";
$c = "Shyam Kumar";
$d = "Sharad Kumar";
echo substr("$a",0, -1)."<br>";
echo substr("$b",2, -1)."<br>";
echo substr("$c",4, -4)."<br>";
echo substr("$d", -3, -1)."<br>";
?>
Output
Basic substr() Usage
Example
<?php
// Accessing single characters in a string
// can also be done using "square brackets"
$string = 'ABCDEF';
echo $string[0]."<br>";
echo $string[3]."<br>";
echo $string[strlen($string)-1];
?>
Output
Casting Behavior substr()
<?php
class MCN {
public function __toString() {
return "PHP";
}
}
echo "1] ".var_export(substr("pear", 0, 2), true).PHP_EOL."<br>";
echo "2] ".var_export(substr(54321, 0, 2), true).PHP_EOL."<br>";
echo "3] ".var_export(substr(new MCN(), 0, 2), true).PHP_EOL."<br>";
echo "4] ".var_export(substr(true, 0, 1), true).PHP_EOL."<br>";
echo "5] ".var_export(substr(false, 0, 1), true).PHP_EOL."<br>";
echo "6] ".var_export(substr("", 0, 1), true).PHP_EOL."<br>";
echo "7] ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL."<br>";
?>
Output