0

trim function delete all more spaces but when try to save data in database it was save with more spaces why pleas help me i but down all code and database construction to help be

CREATE TABLE  `test`.`user` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;

////////////////////////
<?php
    $conn = mysql_connect("localhost","root","");
    if(!$conn){
        die("there is problem in" .mysql_error());
    }
    $select_db = mysql_select_db("test",$conn);
    if(!$select_db){
        die("there is problem in" .mysql_error());
    }
?>
<?php
if(isset($_POST["submit"])){
    $fname = trim($_POST["text"]);
    $name = trim($fname);
    $insert = mysql_query("insert into user(username)values('{$name}')");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<form action="" method="post">
<input type="text" name="text" value=""/>
<input type="submit" name="submit" value="submit"/>
</form>
<body>
</body>
</html>
Tasawer Khan
  • 5,994
  • 7
  • 46
  • 69
Kareem Nour Emam
  • 1,054
  • 4
  • 14
  • 27
  • You should show us the data you're using, and the results your getting. Also, never put unescaped data in a query. – Andrew Jan 14 '11 at 21:35
  • 1
    I'm under the impression you think that trim removes spaces within the word instead of just before/after. – Brad Christie Jan 14 '11 at 21:35
  • 1
    Note: there is no purpose to trimming your data twice `$fname = trim($_POST["text"]); $name = trim($fname);`. Just do `$name = trim($_POST["text"]);` – brian_d Jan 14 '11 at 21:35

2 Answers2

3

The trim function only removes leading and trailing spaces, not double spaces within the text. You can use preg_replace for that, e.g.:

$output = preg_replace('!\s+!', ' ', $input);

Source: php Replacing multiple spaces with a single space

Community
  • 1
  • 1
Alec
  • 9,000
  • 9
  • 39
  • 43
  • wow thanks could u pleas tell me name of the book or site learn me regular exp? – Kareem Nour Emam Jan 14 '11 at 22:47
  • A great place to start is by watching the [Regular Expressions for Dummies](http://blog.themeforest.net/screencasts/regular-expressions-for-dummies/) screencast (here are [parts 2-5](http://blog.themeforest.net/?s=regex+for+dummies)). There's also a good tutorial on [regular-expressions.info](http://www.regular-expressions.info/tutorial.html), and you can easily test regex online with [RegExr](http://gskinner.com/RegExr/). – Alec Jan 15 '11 at 01:07
1

Even simpler than using regex

$without_spaces = str_replace(" ", "", $_POST["text"]);
brian_d
  • 11,190
  • 5
  • 47
  • 72