Johnson
Johnson

Reputation: 818

PHP: Stripping space, but not the space in the middle?

How can i strip spaces/whitespaces $full_name, while i have this:

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

Or maybe you should strip the spaces of the $firstname, $lastname ?

Right now i have these issues i want to fix: If you search with space before nickname e.g " Jackson" then it will just show every row in the db.

If you just enter a space in the field (called) $_POST["search"] it will also show every row in the db.

Here's my full code at the moment:

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;

}

Upvotes: 0

Views: 117

Answers (3)

Wrikken
Wrikken

Reputation: 70460

Optionally, if you don't want spaces, empty tabs, etc. to clutter your split, you can use:

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

Which will split on any amount of whitespace (space, tab, newline), and won't return empty results.

Upvotes: 0

Stewie
Stewie

Reputation: 3121

Won't trim() work.. I didn't read the whole content, but from your question I think that trim() would work

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

Upvotes: 0

Ascherer
Ascherer

Reputation: 8083

trim() rtrim() and ltrim() on $full_name

$full_name = trim($full_name);

Upvotes: 2

Related Questions