I want to detect if a string contains both numbers and letters.
For example:
PncC1KECj4pPVW
, it would be written to a text file because it contains both.qdEQ
, it would not, because it only contains letters.Is there a method to do this?
I was trying to use
$string = PREG_REPLACE("/[^0-9a-zA-Z]/i", '', $buffer);
But it didn't work.
Any help would be appreciated.
Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.
We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.
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.
It seems the simplest way is just to do it in two regex's.
if (preg_match('/[A-Za-z]/', $myString) && preg_match('/[0-9]/', $myString)) { echo 'Contains at least one letter and one number'; }
I suppose another way to do it is this below. It says "a letter and then later on at some point a number (or vice versa)". But the one above is easier to read IMO.
if (preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $myString)) { echo 'Contains at least one letter and one number'; }
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