请帮我修改php修饰功能

时间:2011-01-14 21:30:23

标签: php sql mysql

trim函数删除所有更多空格,但是当尝试在数据库中保存数据时,它保存了更多空格为什么请求帮助我,但是所有代码和数据库构造都有帮助

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>

2 个答案:

答案 0 :(得分:3)

trim函数只删除前导空格和尾随空格,而不删除文本中的空格。您可以使用preg_replace,例如:

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

来源:php Replacing multiple spaces with a single space

答案 1 :(得分:1)

比使用正则表达式更简单

$without_spaces = str_replace(" ", "", $_POST["text"]);