October 2005
Intermediate to advanced
372 pages
11h 35m
English
substr()
string substr ( stringstr, intstart_pos[, intlength] )
The substr()
function allows you to read just part of a string and takes a minimum of two parameters: the string to work with, and where you want to start reading from. There is an optional third parameter to specify how many characters you want to read. Here are some examples of basic usage:
$message = "Goodbye, Perl!";
$a = substr($message, 1);
// $a contains "oodbye, Perl!" - strings and arrays start at 0
// rather than 1, so it copied from the second character onwards.
$b = substr($message, 0);
// $b contains the full string because we started at index 0
$c = substr($message, 5);
// $c copies from index 5 (the sixth character),
// and so will be set to "ye, Perl!"
$d = substr($message, 50);
// $d starts from index 50, which clearly does not exist.
// PHP will return an empty string rather than an error.
$e = substr($message, 5, 4);
// $e uses the third parameter, starting from index five
// and copying four characters. $e will be set to "ye, ",
// a four-letter word with a space at the end.
$f = substr($message, 10, 1);
// $f has 1 character being copied from index 10, which gives "e"You can specify a negative number as parameter three for the length, and PHP will consider that number the amount of characters you wish to omit from the end of the string, as opposed to the number of characters you wish to copy:
$string = "Goodbye, Perl!"; $a = substr($string, 5, 5); // copies five characters from ...