Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

substr()

Synopsis

    string substr ( string str, int start_pos [, int length] )

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page