Featured Posts

How to Trim Blanks from a String using PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 23-11-2009

0

Use ltrim( ), rtrim( ), or trim( ), ltrim( ) 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:

<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>
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 canmake for more
precise display of formatted data or text within<pre> tags, for example. If
you are doing comparisons with userinput, you should trim the data first, so
that someone who mistakenly enters”98052″ as their zip code isn’t forced to
fix an error that really isn’t one. Trimming before exact text comparisons
also ensures that, for example, “salami\n” equals “salami.” It’s also a good
idea to normalize string data bytrimming it before storing it in a database.

The trim( ) functions can also remove user-specifiedcharacters from strings.
Pass the characters you want to remove as a secondargument. You can indicate
a range of characters with two dots between the firstand last characters in
the range:

<?php
// 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( ) asan 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.

VN:F [1.9.3_1094]
Rating: 6.0/10 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
How to Trim Blanks from a String using PHP, 6.0 out of 10 based on 1 rating

Post a comment

You must be logged in to post a comment.