Oleh: dgtola | 30 September 2009

Accessing Substrings

You want to extract part of a string, starting at a particular place in the string. For example,
you want the first eight characters of a username entered into a form.

Solution

Use substr( ) to select your substrings:

$substring = substr($string,$start,$length);
$username = substr($_REQUEST[‘username’],0,8);

Discussion

If $start and $length are positive, substr( ) returns $length characters in the string, starting at $start. The first character in the string is at position 0:

print substr(‘watch out for that tree’,6,5);
out f

If you leave out $length, substr( ) returns the string from $start to the end of the original string:

print substr(‘watch out for that tree’,17);
t tree

If $start plus $length goes past the end of the string, substr( ) returns all of the string from $start forward:

print substr(‘watch out for that tree’,20,5);
ree

If $start is negative, substr( ) counts back from the end of the string to determine where your substring starts:

print substr(‘watch out for that tree’,-6);
print substr(‘watch out for that tree’,-17,5);
t tree
out f

If $length is negative, substr( ) counts back from the end of the string to determine where your substring ends:

print substr(‘watch out for that tree’,15,-2);
print substr(‘watch out for that tree’,-4,-1);
hat tr
tre

#php cookbook#


Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

Kategori

%d blogger menyukai ini: