In JS I used this code:
if(string.match(/[^A-Za-z0-9]+/))
but I don't know, how to do it in PHP.
A ctype_alpha() function in PHP used to check all characters of a given string are alphabetic or not. If all characters are alphabetic then return True otherwise return False.
Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.
There is a very simple way of representing this in PHP. Here is a PHP function which will return true if the string contains english characters or it will return false if there are foreign characters. So, if you were to pass the function: is_english('hello');
Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test(str) . The test method will return true if the string contains only letters and false otherwise.
Answer: Use the PHP strpos() Function. You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false. Also note that string positions start at 0, and not 1.
PHP: Checking if a variable contains only digits For checking if a variable contains only digits, without the commas, periods, positive and negative signs, ctype_digitand preg_matchare the functions you should use instead of is_numeric and is_int.
Here we want to check whether the string $text only consists of letters (a to z and A to Z) and numbers (digits 0 to 9). For this, we use a regular expression and preg_match. As a first parameter, we pass the regular expression, where the actual regular expression is written between "# and #". The symbol ^ represents the beginning of the string.
But your comment inside the if statement // string contains only english letters & digits indicates that you want the code inside the if statement to execute only if the string contains a-z A-Z or 0-9, however by using the ! your code does the opposite. @chap did you see the ^ char at the beginning of the regex?
Use preg_match().
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work. { // string contains only english letters & digits }
if(ctype_alnum($string)) { echo "String contains only letters and numbers."; } else { echo "String doesn't contain only letters and numbers."; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With