user994461
user994461

Reputation: 530

Remove space or blank line at begin

How to remove space or blank line at begin , i have on my site part where users can write description about self, but when u type 10 times space button you can save this in database.. how can i protect to type space at begin or remove ?

example:

                       with space

and

without space (this is good)

This is my code now:

$sql = "UPDATE user SET description='".addslashes(str_replace("\r\n"," ",$_POST[description]))."'";

Upvotes: 0

Views: 2393

Answers (6)

Siyuan Miao
Siyuan Miao

Reputation: 754

You can use the function ltrim if you want to remove the spaces from the beginning.

$sql = "UPDATE user SET description='".addslashes (ltrim(str_replace("\r\n"," ",$_POST[description])))."'";

And if you want to remove the spaces from both the beginning and the end, you can use the function trim.

$sql = "UPDATE user SET description='".addslashes (trim(str_replace("\r\n"," ",$_POST[description])))."'";

Upvotes: 0

Ghostman
Ghostman

Reputation: 6114

You're looking for TRIM.

Upvotes: 0

yehuda
yehuda

Reputation: 1282

To specifically remove from beginning, use

ltrim() 

which removes whitespace from the left

Upvotes: 1

Chris Sobolewski
Chris Sobolewski

Reputation: 12935

$string = '              a string!';
$string = ltrim($string);
echo $string; //outputs 'a string!';

That said, you should really not be injecting user input directly in to your database. Please look at parameterized query or the like. adslashes is not good security.

Edit: ltrim() trims from the left, rtrim() trims from the right, and trim() trims both.

Upvotes: 0

Bjørne Malmanger
Bjørne Malmanger

Reputation: 1477

You can do this:

trim($_POST[description])

Upvotes: 4

No Results Found
No Results Found

Reputation: 102745

This is precisely what trim() does:

$description = trim($_POST['description']);

If you only want the left or right side, use rtrim() or ltrim().

http://php.net/manual/en/function.trim.php

string trim ( string $str [, string $charlist ] )

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

Upvotes: 1

Related Questions