PHP Strings Trimming Blanks from a String - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Strings Trimming Blanks from a String - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Sunday, May 5, 2019

PHP Strings Trimming Blanks from a String

PHP Strings




Trimming Blanks from a String


Problem

You want to remove whitespace from the beginning or end of a string. For example, you want to clean up user input before validating it.



Solution

Use ltrim(), rtrim(), or trim(). The ltrim() function removes whitespace from the
beginning of a string, rtrim() from the end of a string, and trim() from both the
beginning and end of a string:

              $zipcode = trim($_GET['zipcode']);
              $no_linefeed = rtrim($_GET['text']);
              $name = ltrim($_GET['name']);


Discussion

For these functions, whitespace is defined as the following characters: newline, carriage
return, space, horizontal and vertical tab, and null.

Trimming whitespace off of strings saves storage space and can make for more precise
display of formatted data or text within <pre> tags

For example. If you are doing comparisons with user input, you should trim the data first, so that someone who mistakenly enters 98052 followed by a few spaces as their zip code isn’t forced to fix an error that really isn’t one. Trimming before exact text comparisons also ensures 

for example, “salami\n” equals “salami.” It’s also a good idea to normalize string data by trimming it before storing it in a database.

The trim() functions can also remove user-specified characters from strings. Pass the
characters you want to remove as a second argument. You can indicate a range of char‐
acters with two dots between the first and last characters in the range:

              // Remove numerals and space from the beginning of the line
              print ltrim('10 PRINT A$',' 0..9');
              // Remove semicolon from the end of the line
              print rtrim('SELECT * FROM turtles;',';');

This prints:

              PRINT A$
              SELECT * FROM turtles

PHP also provides chop() as an alias for rtrim(). However, you’re best off using
rtrim() instead because PHP’s chop() behaves differently than Perl’s chop() (which is
deprecated in favor of chomp(), anyway), and using it can confuse others when they
read your code.




No comments:

Post a Comment

Post Top Ad