What is the best way to check if the string has any spaces in the first 10 characters?
$value = "cdjfvdkvnfkjvnfjnbjfnjn";
What is the best way to check if the string has any spaces in the first 10 characters?
$value = "cdjfvdkvnfkjvnfjnbjfnjn";
Use strpos()
:
if (strpos(substr($string, 0, 1), ' ') !== FALSE) {
// has whitespace
}
Or preg_match()
:
if(preg_match('/\s/', substr($string, 0, 10))) {
// has whitespace
}
The advantage of preg_match()
over strpos()
is that it can detect any kind of whitespace not just space characters. \s
is a shorthand representation for the character class [
\t\f ]
.