如何测试字符串开头和结尾的空格?
我不想删除空格,我只想返回一个布尔TRUE
或FALSE
如果它们存在。
谢谢。
$string = <your string>;
$ns_string = trim($string);
$spaces_present = ($ns_string == $string) ? false : true;
用较短的符号
$space_present = ($string != trim($string));
这应该适合您:
<?php
$str = "test";
if($str[0] == " "|| $str[strlen($str)-1] == " ")
echo "space at the start or the end";
?>
ctype_space($str[0]) || ctype_space(substr($str, -1))
<?php
$test = 'test ';
if (strpos($test, ' ') === 0 || strpos($test, ' ') === strlen($test)-1) {
return true;
}
?>
编辑:见黑蜂解释
像这样检查
if (substr($str, -1) == " " || $str[0] == " " ) {
}
简单的正则表达式
preg_match("~(^'s|'s$)~", $subject);