检查一个字符串在每个单词之间是否有超过 1 个 space,如果是 return 是否为负
Check if a string has more than 1 space between each word and return negative if so
我有以下字符串:
$name = "John Lucas";
我想设定一个条件,如果 $name
每个单词之间有超过 1 个 space 那么 return false。
关于如何做到这一点有什么想法吗?
更新示例:
<input name="name" type="text"/> //example
<?php
$name = $_REQUEST['name'];
if ( $name has more than 2 spaces between each word ) {
echo 'FALSE';
}
?>
if $name has more than 1 space between each word then return false.
使用preg_match
函数的解决方案:
function hasSingleSpaces($str) {
return (bool) !preg_match("/\w+\s{2,}(?=\w+)/", $str);
}
var_dump(hasSingleSpaces("John Lucas")); // false
var_dump(hasSingleSpaces("John Lucas hello")); // false
var_dump(hasSingleSpaces("John Lucas hello")); // true
我有以下字符串:
$name = "John Lucas";
我想设定一个条件,如果 $name
每个单词之间有超过 1 个 space 那么 return false。
关于如何做到这一点有什么想法吗?
更新示例:
<input name="name" type="text"/> //example
<?php
$name = $_REQUEST['name'];
if ( $name has more than 2 spaces between each word ) {
echo 'FALSE';
}
?>
if $name has more than 1 space between each word then return false.
使用preg_match
函数的解决方案:
function hasSingleSpaces($str) {
return (bool) !preg_match("/\w+\s{2,}(?=\w+)/", $str);
}
var_dump(hasSingleSpaces("John Lucas")); // false
var_dump(hasSingleSpaces("John Lucas hello")); // false
var_dump(hasSingleSpaces("John Lucas hello")); // true