Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - detect whitespace between strings

People also ask

How to validate space in PHP?

The ctype_space() function in PHP check for whitespace character(s). It returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

Is substring in string PHP?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

Which of the following character function is used to check for any printable character which is not whitespace or an alphanumeric character?

The isalnum() method returns: True - if all characters in the string are alphanumeric. False - if at least one character is not alphanumeric.


Use preg_match as suggested by Josh:

<?php

$foo = 'Bob Williams';
$bar = 'SamSpade';
$baz = "Bob\t\t\tWilliams";

var_dump(preg_match('/\s/',$foo));
var_dump(preg_match('/\s/',$bar));
var_dump(preg_match('/\s/',$baz));

Ouputs:

int(1)
int(0)
int(1)

Wouldn't preg_match("/\s/",$string) work? The advantage to this over strpos is that it will detect any whitespace, not just spaces.


You could check for only alphanumerical characters, which whitespace is not. You could also do a strpos for a space.

if(strpos($string, " ") !== false)
{
   // error
}

You may use something like this:

if (strpos($r, ' ') > 0) {
    echo 'A white space exists between the string';
}
else
{
    echo 'There is no white space in the string';
}

This will detect a space, but not any other kind of whitespace.