Home > Software design >  php - How can I check if the sentence consists of a single word?
php - How can I check if the sentence consists of a single word?

Time:12-15

For example;

"Real Madrid" -> false
"Barcelona  " -> true

with what functions can I solve this in laravel?

CodePudding user response:

A string is a single word if it:

  1. contains at least one character
  2. contains no whitespace
function isSingleWord(string $input): bool
{
    // Check for empty string - "" isn't a word
    if (empty($input)) {
        return false;
    }

    // Check for whitespace of any kind
    return !preg_match('/\s/', $input);
}

CodePudding user response:

you can use

$result = explode(' ', trim("barcelona "));
print_r($result);

trim will remove all white space at the beginning and the end of your string

  • Related