PHP: substr()

Substr() is used to return only a certain part of a string, specified by an upper and lower boundary.

PHP SubStr() Prototype

string substr ( string string, int start [, int length] )

String (return value): This is the piece of the string that lies between the given boundaries, and will be returned by substr().

String (parameter): This is the string that contains the subset of characters we want to return using substr().

Start: This indicates how many positions from the beginning we want to start returning from. Alternatively, if this is a negative number, i.e -x, it will start returning x positions from the end.

Length: This is optional. This represents how many characters from the start position we wish to return. If this is given as a negative, substr() will stop returning characters from that many positions from the end.

How to Use SubStr() in PHP

Let's say we have a string:

$name = "//John Doe/";

Assume we want to return the name, without the delimiting slashes. This means we want to start 2 positions from the left (after the second "/") and stop 1 position before the end (before the last "/"). We would do this using substr() as follows:

$name = substr($name, 2, 8);

$name should now contain "John Doe".

Now, what if we don't know the length of the characters we want to return, but we do know we want to leave off the last "/"? In that case, use substr() in this way:

$name = substr($name, 2, -1);

This will accomplish the same thing.

Leave a comment
Name:

Comment:

 
Total comments: 12
rofl commented on 6 Feb 2007 -
thx
andrius commented on 18 Apr 2007 -
A strange web site this is. Found in google by mistake :), forgot to put a space between "php" and "substr".
alex commented on 22 Jun 2007 -
Hmmm... I have to agree with andrius, what a strange little site. Totally useful though. Thanks!
christoph commented on 26 Jun 2007 -
this is the strangest
peppe commented on 27 Jun 2007 -
funny thing :)
Wonderer commented on 20 Aug 2007 -
What else do you have on this site?
:|
cowcow commented on 27 Nov 2007 -
the second example suppose is: $name = substr($name, -1); will return "/"
not $name = substr($name, 2, -1); this will return "John Doe"
am i right?
or this is what we want?
oic..i think i know..hehe:)
JIm commented on 22 Jan 2008 -
LOL, weird but at least somehow useful
Jamie commented on 6 Apr 2008 -
Thanks alot, just what I needed!
vijay commented on 29 Apr 2008 -
thanx!
sivakarthikeyan commented on 31 May 2008 -
nice work thanks
Holy commented on 23 Jun 2008 -
Wow, thats hilarious