Recipe 1.2. Extracting Substrings


1.2.1. Problem

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.

1.2.2. Solution

Use substr( ) to select your substring, as in Example 1-9.

Extracting a substring with substr( )

<?php $substring = substr($string,$start,$length); $username = substr($_GET['username'],0,8); ?>

1.2.3. 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. Example 1-10 has positive $start and $length.

Using substr( ) with positive $start and $length

print substr('watch out for that tree',6,5);

Example 1-10 prints:

out f

If you leave out $length, substr( ) returns the string from $start to the end of the original string, as shown in Example 1-11.

Using substr( ) with positive start and no length

print substr('watch out for that tree',17);

Example 1-11 prints:

t tree

If $start is bigger than the length of the string, substr( ) returns false..

If $start plus $length goes past the end of the string, substr( ) returns all of the string from $start forward, as shown in Example 1-12.

Using substr( ) with length past the end of the string

print substr('watch out for that tree',20,5); 

Example 1-12 prints:

ree

If $start is negative, substr( ) counts back from the end of the string to determine where your substring starts, as shown in Example 1-13.

Using substr( ) with negative start

print substr('watch out for that tree',-6); print substr('watch out for that tree',-17,5); 

Example 1-13 prints:

t tree out f

With a negative $start value that goes past the beginning of the string (for example, if $start is -27 with a 20-character string), substr( ) behaves as if $start is 0.

If $length is negative, substr( ) counts back from the end of the string to determine where your substring ends, as shown in Example 1-14.

Using substr( ) with negative length

print substr('watch out for that tree',15,-2); print substr('watch out for that tree',-4,-1); 

Example 1-14 prints:

hat tr tre

1.2.4. See Also

Documentation on substr( ) at http://www.php.net/substr.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net