Reputation: 1998
How do I test for whitespace at the beginning and end of a string?
I don't want to remove spaces, I just want a boolean TRUE
or FALSE
returned if they exist.
Thanks.
Upvotes: 1
Views: 1534
Reputation: 2934
Check like this
if (substr($str, -1) == " " || $str[0] == " " ) {
}
Upvotes: 1
Reputation: 681
<?php
$test = 'test ';
if (strpos($test, ' ') === 0 || strpos($test, ' ') === strlen($test)-1) {
return true;
}
?>
EDIT: See darkbees explaination
Upvotes: 1
Reputation: 3925
$string = <your string>;
$ns_string = trim($string);
$spaces_present = ($ns_string == $string) ? false : true;
in shorter notation
$space_present = ($string != trim($string));
Upvotes: 7
Reputation: 59681
This should work for you:
<?php
$str = "test";
if($str[0] == " "|| $str[strlen($str)-1] == " ")
echo "space at the start or the end";
?>
Upvotes: 4