如何在PHP中检测空空间?
如何检测字符串中由于输入多个空格键而产生的所有空格 换句话说,我不想检测到这一点:如何在PHP中检测空空间?,php,Php,如何检测字符串中由于输入多个空格键而产生的所有空格 换句话说,我不想检测到这一点: " " 但还有比这更重要的。例如: " ", " ", etc... 您可以使用正则表达式: $regex = '~\s{2,}~'; preg_match($regex, $str); \s包括空白、制表符和新行。如果只需要空格,可以将$regex更改为: $regex = '~ {2,}~'; 如果要从字符串中删除额外空格,可以使用: $str = 'hello there, world
" "
但还有比这更重要的。例如:
" ", " ", etc...
您可以使用正则表达式:
$regex = '~\s{2,}~';
preg_match($regex, $str);
\s
包括空白、制表符和新行。如果只需要空格,可以将$regex
更改为:
$regex = '~ {2,}~';
如果要从字符串中删除额外空格,可以使用:
$str = 'hello there, world!';
$regex = '~ {2,}~';
$str = preg_replace($regex, ' ', $str);
echo $str;
$input = "foo bar baz saz";
if(preg_match_all('/\s{2,}/',$input,$matches)) {
var_dump($matches);
}
产出:
hello there, world!
您可以使用:
$str = 'hello there, world!';
$regex = '~ {2,}~';
$str = preg_replace($regex, ' ', $str);
echo $str;
$input = "foo bar baz saz";
if(preg_match_all('/\s{2,}/',$input,$matches)) {
var_dump($matches);
}
输出:
array(1) {
[0]=>
array(2) {
[0]=>
string(2) " "
[1]=>
string(3) " "
}
}
\s
表示空白,包括空格、垂直制表符、水平制表符、返回框、换行符、换页符
如果只想匹配普通空格,可以使用正则表达式:
if(preg_match_all('/ {2,}/',$input,$matches)) {
@博尔特:我用波浪形,有时用感叹号。我从不使用正斜杠=/当我们每天在这么多的支票中匹配正斜杠时,这绝对令人恶心:/