PHP - detect whitespace between strings

后端 未结 7 2311
情书的邮戳
情书的邮戳 2020-12-03 09:42

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 re

相关标签:
7条回答
  • 2020-12-03 10:26

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

    0 讨论(0)
  • 2020-12-03 10:27
    // 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);
    }
    
    0 讨论(0)
  • 2020-12-03 10:33

    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.

    0 讨论(0)
  • 2020-12-03 10:37

    Use preg_match as suggested by Josh:

    <?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)
    
    0 讨论(0)
  • 2020-12-03 10:38

    http://no.php.net/strpos

    <?php
    if(strpos('Jane Doe', ' ') > 0)
        echo 'Including space';
    else
        echo 'Without space';
    ?>
    
    0 讨论(0)
  • 2020-12-03 10:39

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

    if(strpos($string, " ") !== false)
    {
       // error
    }
    
    0 讨论(0)
提交回复
热议问题