Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > Playing with strings Wish List | Report Bug | About Me ]

4.7.1     Reading from part of a string: substr()

This is NOT the latest copy of this book; click here for the latest version.

string substr ( string source, int start [, 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 allow you to specify how many characters you want to read (the length you want to copy). Here are some examples of basic usage:

<?php
    $string
= "Goodbye, Perl!";
    
$a = substr($string, 1);
    
$b = substr($string, 0);
    
$c = substr($string, 5);
    
$d = substr($string, 50);
    
$e = substr($string, 5, 4);
    
$f = substr($string, 10, 1);

?>

After that code executes, $a will contain "oodbye, Perl!" If you were expecting it to return the full string, do not worry - it is a common mistake. In PHP, strings an arrays start at 0 rather than 1, and, as we specified 1 as parameter two to substr(), it started copying from the second character and took all the letters to the end of the string.

With $b we get the expected behaviour, the entire string is copied, because we started at index 0. $c has us copying from index 5 (the sixth character), and so $c will be set to "ye, Perl!", as expected. With $d we start from index 50 (the 51st character) in the string "Goodbye, Perl!", which clearly does not exist. This line is in there to show you that even if you try to copy more than you have, PHP will not return an error - it will just return an empty string.

With $e we start using the third parameter. With 5 as parameter two and 4 as parameter 3, substr() should start from index five (the sixth character) and copy four characters. If you try it, you will see that it does just that - substr($string, 5, 4) returns the string "ye, ", a four-letter word with a space making up the last character.

Finally, with variable $f, we have 1 character being copied from index 10, which stores "e" in $f.

So far, so good. However, we're not finished - substr() can do more. For example, 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. Consider this script:

<?php
    $string
= "Goodbye, Perl!";
    
$a = substr($string, 5, 5);
    
$b = substr($string, 5, -1);
    
$c = substr($string, 0, -7);
?>

$a is quite straightforward, and copies five characters from index five onwards, giving "ye, P". However, $b and $c both use negative lengths, which mean that they take all the string except for length characters at the end. So, $b is set to "ye, Perl", and $c is set to "Goodbye". Using negative lengths allows you to say "copy everything but the last three characters".

But wait - there is even more! You can also use a negative start index, in which case you start copying start characters from the end. You can even use a negative length with your negative start index. Here are some examples that should hopefully make things clear:

<?php
    $string
= "Goodbye, Perl!"
    
$a = substr($string, 5);
    
$b = substr($string, 5, 5);
    
$c = substr($string, 0, -1);
    
$d = substr($string, -5);
    
$e = substr($string, -5, 4);
    
$f = substr($string, -5, -4);
?>

That chunk of code demonstrates each possible way to use substr(). You already know how $a, b, and $c work - copy from character five till end, copy five characters from character five, and copy all but the last character respectively.

With $d, we start using a negative start value for parameter 2, -5. After running the code, $d will be set to "Perl!", because PHP will start 5 characters from the end of the string, then copy from there till the end of the string. With $e we specify a negative start and a positive length, with the end result being that PHP will start five characters from the end of the string ("P"), then copy four characters, meaning that $e will be set to "Perl".

Finally, with $f, we have both a negative start value and a negative length, which translates as "start five characters from the end of the string, and copy everything but the last four". As we're starting five from the end and we are asking PHP not to copy the last four, we are in fact copying just one character, "P", which, if you run the script, will be what $f ends up containing. Marvellous.





<< 4.7 Playing with strings   4.7.2 Replacing parts of a string: str_replace() and str_ireplace() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
aseffamit@gmail.com - 07 Sep 2008

how do i carry out for a very large string with negative index, i.e
$str="hello";
substr($str,-6) returns empty.
how do i handle such kinds of code.

A PHP User - 07 Sep 2008

All of this information and more can be found at www.php.net
Very concise description, however. Useful for validating file extensions.

Siambic Pentameter - 07 Sep 2008

Top notch humor guys.
There are better free ebooks out there by the way, keep looking.

A PHP User - 07 Sep 2008

Thank you, I was looking all over for a way to check to see if a submitted url ended in .gif
I've used:
$string = 'http://www.example.com/img/car.gif';

$d = substr($string, -4);

if ($d == '.gif') {
$valid = 'yes';
} else {
$valid = 'no';
}

I also used it to see if the url started in http


Thank you

Siamey's Mom - 07 Sep 2008

Siamey, i tol' you, an iq of -2 don' give you no right to make fun of those with -3

deathgod - 07 Sep 2008

Siamey perhaps you should not say anything if you are going to be an ass. We have all found something hard that others found easy in this book. Perhaps he has been going through this non-stop since the chapter3 or something. So stop being an ass.

A PHP User - 07 Sep 2008

there is no need for insults
sometimes i also have to read twice to get it...
perhaps english is not his native language?!

Siamey - 07 Sep 2008

"A |\| 3 \/\/ 13 | E PHP User" must be retarded, because this page is very well written and well explained.

Even when I was slightly confused by the new negative parameters and how they work, the author went on to explain it in detail, and I soon understood.

A PHP User - 07 Sep 2008

good work.

krany - 07 Sep 2008

The author did an excellent explanation.

A PHP User - 07 Sep 2008

The last example has a missing semicolon on the string line,
thus PHP will error with that example as it's written

e.g.
$string = "Goodbye, Perl!"

should be

$string = "Goodbye, Perl!";

A |\| 3 \/\/ 13 | E PHP User - 07 Sep 2008

A Bit Hard To Understand :\

l_padmapriya@rediffmail.com - 07 Sep 2008

Very Excellent Chapter! Really I am enjoy it.

A PHP User - 07 Sep 2008

So when you use negative numbers, the functions treats them as distance from the back instead of distance from the front.

Your explanation is a bit overkill.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is nine plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow