How to check, if a php string contains only english letters and digits?

前端 未结 9 1579
既然无缘
既然无缘 2020-11-30 01:33

In JS I used this code:

if(string.match(/[^A-Za-z0-9]+/))

but I don\'t know, how to do it in PHP.

相关标签:
9条回答
  • 2020-11-30 02:01
    if(preg_match('/[^A-Za-z0-9]+/', $str)) {
        // ...
    }
    
    0 讨论(0)
  • 2020-11-30 02:02

    Use preg_match().

    if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
    {
      // string contains only english letters & digits
    }
    
    0 讨论(0)
  • 2020-11-30 02:09

    if you need to check if it is English or not. you could use below function. might help someone..

    function is_english($str)
    {
        if (strlen($str) != strlen(utf8_decode($str))) {
            return false;
        } else {
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:10
    if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
    // $string constains both string and integer
    }
    

    The carrot was in the wrong place so it would have search for everything but what is inside the square brackets. When the carrot is outside it searches for what is in the square brackets.

    0 讨论(0)
  • 2020-11-30 02:13

    You can use preg_match() function for example.

    if (preg_match('/[^A-Za-z0-9]+/', $str))
    {
      // ok...
    }
    
    0 讨论(0)
  • 2020-11-30 02:19
    if(ctype_alnum($string)) {
        echo "String contains only letters and numbers.";
    }
    else {
        echo "String doesn't contain only letters and numbers.";
    }
    
    0 讨论(0)
提交回复
热议问题