PHP:剥离空间,但不是中间的空间?

时间:2010-09-29 19:40:40

标签: php

我如何删除空格/空格$ full_name,而我有这个:

list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name, 2));

或许您应该删除$ firstname的空格,$ lastname?

现在我想解决这些问题: 如果你在昵称之前用空格搜索,例如“杰克逊”,那么它只会显示数据库中的每一行。

如果您只是在字段中输入一个空格(称为)$ _POST [“search”],它也会显示数据库中的每一行。

这是我目前的完整代码:

if(isset($_POST["search"]) && !empty($_POST["search"])) {
$full_name = strtolower(mysql_real_escape_string($_POST["search"]));
$sex = mysql_real_escape_string($_POST["sex"]);

list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name, 2));

if (!$lastname) $lastname = $firstname;
    $query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')"; 
if(!empty($sex))
{
    $sql .= "AND sex = '$sex'";
}
$result1 = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result1);

while($get = mysql_fetch_array  ($result1)){
$Matchy = $get["firstname"] . " " . $get["lastname"];

$Matchy = str_replace(" ","",strtolower($Matchy));

if(str_replace(" ","",strtolower($full_name)) == $Matchy){
    echo "Match fully, redirect..";
    }

$re_fname='<b>'.$firstname.'</b>'; 
$re_lname='<b>'.$lastname.'</b>';
$final_fname = str_ireplace($firstname, $re_fname, $get["firstname"]);

$final_lname = str_ireplace($lastname, $re_lname, $get["lastname"]);
echo $final_fname . " " .$final_lname."<br>";
}
  echo "You searched for " . $firstname . " ". $lastname ." with sex: ". $sex . "  results: " .$count;

}

3 个答案:

答案 0 :(得分:2)

$ full_name上的trim()rtrim()和ltrim()

$ full_name = trim($ full_name);

答案 1 :(得分:0)

不会修剪()工作..我没有阅读整个内容,但从你的问题我认为trim()会起作用

$full_name = trim(strtolower(mysql_real_escape_string($_POST["search"])));

答案 2 :(得分:0)

或者,如果您不想要空格,空标签等以使分割混乱,您可以使用:

list($firstname, $lastname) = array_map('ucfirst',
    preg_split('/\s+/',$full_name, 2,PREG_SPLIT_NO_EMPTY));

将分割任意数量的空格(空格,制表符,换行符),并且不会返回空结果。