PHP - 检测字符串之间的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1161708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:17:22  来源:igfitidea点击:

PHP - detect whitespace between strings

phpregexwhitespace

提问by hobodave

How would I go about detecting whitespace within a string? For example, I have a name string like:

我将如何检测字符串中的空格?例如,我有一个名称字符串,如:

"Jane Doe"

“简·多”

Keep in mind that I don't want to trim or replace it, just detect if whitespace exists between the first and second string.

请记住,我不想修剪或替换它,只需检测第一个和第二个字符串之间是否存在空格。

回答by hobodave

Use preg_match as suggested by Josh:

按照 Josh 的建议使用 preg_match:

<?php

$foo = "Dave Smith";
$bar = "SamSpade";
$baz = "Dave\t\t\tSmith";

var_dump(preg_match('/\s/',$foo));
var_dump(preg_match('/\s/',$bar));
var_dump(preg_match('/\s/',$baz));

Ouputs:

输出:

int(1)
int(0)
int(1)

回答by Tyler Carter

You could check for only alphanumerical characters, which whitespace is not. You could also do a strpos for a space.

您只能检查字母数字字符,而空白则不是。你也可以为一个空间做一个 strpos 。

if(strpos($string, " ") !== false)
{
   // error
}

回答by Josh

Wouldn't preg_match("/\s/",$string)work? The advantage to this over strpos is that it will detect any whitespace, not just spaces.

不会的preg_match( “/ \ s /”,$弦)工作?与 strpos 相比,它的优势在于它会检测任何空格,而不仅仅是空格。

回答by gurjeet kj

You may use something like this:

你可以使用这样的东西:

if (strpos($r, ' ') > 0) {
    echo 'A white space exists between the string';
}
else
{
    echo 'There is no white space in the string';
}

This will detect a space, but not any other kind of whitespace.

这将检测一个空格,但不会检测任何其他类型的空格。

回答by ThoKra

http://no.php.net/strpos

http://no.php.net/strpos

<?php
if(strpos('Jane Doe', ' ') > 0)
    echo 'Including space';
else
    echo 'Without space';
?>

回答by Rachel

// returns no. of matches if $str has nothing but alphabets,digits and spaces.
function is_alnumspace($str){
  return preg_match('/^[a-z0-9 ]+$/i',$str);
}

回答by Interesting Articles

// returns no. of matches if $str has nothing but alphabets,digits and spaces. function 

    is_alnumspace($str) {
          return preg_match('/^[A-Za-z0-9 ]+$/i',$str);
    }

// This variation allows uppercase and lowercase letters.