Substr
(PHP 4, PHP 5)
substr-returns a substring of a string
Description
String substr (string $string, int $start [, int $length])
Returns a substring string string that is specified by the start and length arguments.
Parameters
String
The input string.
Start
If Start is Non-negative, the returned string starts at the start position of string and is calculated starting at 0. For example, in the string "ABCdef", the character at position 0 is "a", and the string at position 2 is "C" and so on.
If start is a negative number, the returned string starts with the first character starting at the end of the string.
Returns FALSE if the length of a string is less than or equal to start.
Example #1 Use negative start
<?php
$rest = substr ("abcdef",-1); Return "F"
$rest = substr ("ABCdef",-2); Return to "EF"
$rest = substr ("ABCdef",-3, 1); Return "D"
?>
Length
If the length of a positive number is provided, the returned string will start at the beginning with a maximum of length characters (depending on the length of the string).
If a negative length is provided, many characters at the end of the string are omitted (if start is a negative number from the tail of the string). If start is not in this text, an empty string is returned.
If length is provided with a value of 0,false or NULL, an empty string is returned.
If length is not supplied, the returned substring starts at the start position until the end of the string.
Example #2 Use negative length
<?php
$rest = substr ("abcdef", 0,-1); Return to "ABCDE"
$rest = substr ("ABCdef", 2,-1); Back to "CDE"
$rest = substr ("ABCdef", 4,-4); Returns ""
$rest = substr ("ABCdef",-3,-1); Return to "de"
?>
return value
Returns the extracted substring or FALSE when it fails.
Example
Example #3 substr () Basic usage
<?php
echo substr (' abcdef ', 1); Bcdef
echo substr (' abcdef ', 1, 3); Bcd
echo substr (' abcdef ', 0, 4); Abcd
echo substr (' abcdef ', 0, 8); ABCdef
echo substr (' abcdef ',-1, 1); F
To access a single character in a string
You can also use the brackets
$string = ' abcdef ';
echo $string [0]; A
Echo $string [3]; D
echo $string [Strlen ($string)-1]; F
?>
Error/exception
Returns False when the error occurs. <?php
Var_dump (substr (' A ', 1)); BOOL (FALSE)
?>