1.8 Removing Whitespace from a String


You want to trim blanks from the beginning or end of your string.

Technique

Use the chop() or rtrim () function to remove whitespace from the end of the string:

 <?php $str = "red apple   "; // Get rid of that trailing whitespace $str = chop ($str); // analogous to rtrim ($str); ?> 

You can use the ltrim () function to remove whitespace from the beginning of a string:

 <?php $str = '   Knock, Knock?'; $str = ltrim ($str); // Get rid of leading whitespace ?> 

Comments

Perl programmers should be careful: The PHP chop() function is a little different from Perl's chop function. PHP's chop() function is equivalent to Perl's chomp() function. That is, it removes whitespace only from the end of a string, instead of arbitrarily removing any character.

If you want to remove the whitespace from the beginning and end of a string, you could use a combination of ltrim() and chop() . However, more efficiently , you could just use the trim() function:

 <?php $str = "   This is a story about dogs...   "; $str = trim ($str); // All whitespace from the beginning and end is removed ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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