2015-05-09 63 views
-1

所以我有一個輸入表單,用戶輸入用戶名後,網站會收集基於用戶名的信息,但是,如果用戶名中有空格,用戶名變爲無效(不存在)。我將如何添加一個PHP中的行爲來擺脫任何空間和所有空間,以便最終提交的用戶名是john doe而不是johndoe如何從輸入表單中刪除空格提交


這裏是我的表單代碼:

<form action="php.php" method="GET"> 
    <div class="form-group"> 
    <label for="username">Username:</label> 
    <input type="text" class="form-control" id="username" name="username" placeholder="Enter username" required> 
    </div> 
    <button type="submit" class="btn btn-default">Submit</button> 
</form> 

而這裏的php.php文件代碼:

//I GUESS THIS IS WHERE THE TRIMMING SHOULD HAPPEN? 
<?php 
//error_reporting(E_ALL & ~E_NOTICE); 
// Load the username from somewhere 
if (
$username = $_GET["username"] 
) { 
    //do nothing 
} else { 
    //$username = "notch"; 
    echo "Oops! Something went wrong!"; 
} 
?> 
+0

你說的是中間的前後空格或空格嗎? –

+0

可能重複的[在PHP中刪除變量中的空格](http://stackoverflow.com/questions/1279774/to-strip-whitespaces-inside-a-variable-in-php)或[如何去除所有空格出了一個字符串在PHP?](http://stackoverflow.com/questions/2109325/how-to-strip-all-spaces-out-of-a-string-in-php) – Sean

+1

順便說一句,這條線會失敗因爲2個原因'if( $ username = $ _GET [「username」] )' –

回答

3

使用字符串替換函數替換空間中出現的所有帶有字符串空串(無):

<?php 
$string = 'My Name'; 
$noSpaces = str_replace(' ', '', $string); 
echo $noSpaces; // echos 'MyName' 
?> 
+0

因此,在我的情況下,我會簡單地執行'$ username = str_replace('','',$ string);'? – JLWillliamsUK

+0

是的,'$ username'現在不包含空格 – mattfryercom

+0

是的。謝謝,這就是訣竅!將在4分鐘內標出,因爲那時它也會允許我! – JLWillliamsUK

2

1.如果您在說引導或尾隨空格,則使用trim()函數。

$username =trim($username); 

但是,如果你談論的是中間的空間,然後用preg_replace()做到: -

$username = preg_replace('/\s+/', ' ', $username); 

您可以string_replace也走 -

$username = str_replce(' ','',$username); 

注意: -這裏$username是你打算使用的用戶名。

此外,您可以先與第二個或第三個合併,以獲得完全乾淨的用戶名,而不需要前導後綴和中間空格。像這樣: -

$username = trim(preg_replace('/\s+/', ' ', $username)); 
+1

是的,我說的是領先和尾隨空格:) – JLWillliamsUK

+1

'str_replce'有一個輸入錯誤 –

+0

@JWWilllliamsUK你說'是的,我在說引導和尾隨空格:''那麼爲什麼你標記在上面的答案?這是錯誤的,因爲它也會刪除中間的空格。 –