PHP - make sure string has no whitespace

This solution is for the inverse problem: to know if a string contains at least one word.

/**
 * 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;
}

If the function return false there are no words in the $input_string. So, you can do something like that:

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

Try this too :

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

Try this method:

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

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

Tags:

Php