Подтвердить что ты не робот

PHP - убедитесь, что строка не имеет пробелов

Как проверить, содержит ли строка PHP пробел? Я хочу проверить, есть ли там пробел, а затем отсылать сообщение об ошибке, если true

if(strlen($username) == whitespace ){

                echo "<center>Your username must not contain any whitespace</center>";
4b9b3361

Ответ 1

if ( preg_match('/\s/',$username) ) ....

Ответ 2

Это решение для обратной задачи: знать, содержит ли строка хотя бы одно слово.

/**
 * Check if a string contains at least one word.
 *
 * @param string $input_string
 * @return boolean
 *  true if there is at least one word, false otherwise.
 */    
function contains_at_least_one_word($input_string) {
  foreach (explode(' ', $input_string) as $word) {
    if (!empty($word)) {
      return true;
    }
  }
  return false;
}

Если функция возвращает false, в строке $input_string нет слов. Итак, вы можете сделать что-то вроде этого:

if (!contains_at_least_one_word($my_string)) {
  echo $my_string . " doesn't contain any words.";
}

Ответ 3

Попробуйте этот метод:

if(strlen(trim($username)) == strlen($username)) {
  // some white spaces are there.
}

Ответ 4

Попробуйте следующее:

if ( preg_match('/\s/',$string) ){
    echo "yes $string contain whitespace";  
} else {
    echo "$string clear no whitespace ";    
}

Ответ 5

Попробуйте также:

if (count(explode(' ', $username)) > 1) {
  // some white spaces are there.
}

Ответ 6

PHP предоставляет встроенную функцию ctype_space( string $text ) для проверки пробельных символов. Тем не менее, ctype_space() проверяет, создает ли символ каждый строку. В вашем случае вы можете сделать функцию, аналогичную следующей, чтобы проверить, есть ли строка с пробельными символами.

/**
 * Checks string for whitespace characters.
 *
 * @param string $text
 *   The string to test.
 * @return bool
 *   TRUE if any character creates some sort of whitespace; otherwise, FALSE.
 */
function hasWhitespace( $text )
{
    for ( $idx = 0; $idx < strlen( $text ); $idx += 1 )
        if ( ctype_space( $text[ $idx ] ) )
            return TRUE;

    return FALSE;
}

Ответ 7

Другой метод:

$string = "This string have whitespace";
if( $string !== str_replace(' ','',$string) ){
    //Have whitespace
}else{
     //dont have whitespace
}