How do I detect non-ASCII characters in a string?

前端 未结 9 2252
面向向阳花
面向向阳花 2020-12-01 07:56

If I have a PHP string, how can I determine if it contains at least one non-ASCII character or not, in an efficient way? And by non-ASCII character, I mean any character tha

相关标签:
9条回答
  • 2020-12-01 08:15

    I found it more useful to detect if any character falls out of the list

    if(preg_match('/[^\x20-\x7e]/', $string))
    
    0 讨论(0)
  • 2020-12-01 08:22

    You could use:

    mb_detect_encoding

    but it will be maybe not as precise as you want it to be.

    0 讨论(0)
  • 2020-12-01 08:24

    Try: (Source)

    function is_ascii( $string = '' ) {
        return ( bool ) ! preg_match( '/[\\x80-\\xff]+/' , $string );
    }
    

    Although, all of the above answers are correct, but depending upon the input, these solutions may give wrong answers. See the last section in this ASCII validation post.

    0 讨论(0)
提交回复
热议问题