Eddy Unruh
Eddy Unruh

Reputation: 616

PHP check if string contains space between words (not at beginning or end)

I need to check if a string contains a space between words, but not at beginning or end. Let's say there are these strings:

1: "how r u ";
2: "how r u";
3: " howru";

Then only 2 should be true. How could I do that?

Upvotes: 16

Views: 61580

Answers (3)

Don't Panic
Don't Panic

Reputation: 41820

You can verify that the trimmed string is equal to the original string and then use strpos or str_contains to find a space.

// PHP < 8
if ($str == trim($str) && strpos($str, ' ') !== false) {
    echo 'has spaces, but not at beginning or end';
}

// PHP 8+
if ($str == trim($str) && str_contains($str, ' ')) {
    echo 'has spaces, but not at beginning or end';
}

Some more info if you're interested

If you use strpos(), in this case, you don't have to use the strict comparison to false that's usually necessary when checking for a substring that way. That comparison is usually needed because if the string starts with the substring, strpos() will return 0, which evaluates as false.

Here it is impossible for strpos() to return 0, because the initial comparison
$str == trim($str) eliminates the possibility that the string starts with a space, so you can also use this if you like:

if ($str == trim($str) && strpos($str, ' ')) { ...

If you want to use a regular expression, you can use this to check specifically for space characters:

if (preg_match('/^[^ ].* .*[^ ]$/', $str) { ...

Or this to check for any whitespace characters:

if (preg_match('/^\S.*\s.*\S$/', $str) { ...

I did some simple testing (just timing repeated execution of this code fragment) and the trim/strpos solution was about twice as fast as the preg_match solution, but I'm no regex master, so it's certainly possible that the expression could be optimized to improve the performance.

Upvotes: 43

Toto
Toto

Reputation: 91518

If your string is at least two character long, you could use:

if (preg_match('/^\S.*\S$/', $str)) {
    echo "begins and ends with character other than space";
} else {
    echo "begins or ends with space";
}

Where \S stands for any character that is not a space.

Upvotes: 4

user3394825
user3394825

Reputation: 21

you can acces letter in a array

for($i = 1 ; i < strlen($word)-1 ; $i++ )
{
 if($word[$i] = " " ;
 {
  echo "space" ;
 }
}

Upvotes: 0

Related Questions