Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains numbers and letters

Tags:

php

I want to detect if a string contains both numbers and letters.

For example:

  • Given PncC1KECj4pPVW, it would be written to a text file because it contains both.
  • Given 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.

like image 420
Duncan Palmer Avatar asked Feb 17 '12 21:02

Duncan Palmer


People also ask

How do you check if a string contains numbers and letters in Python?

Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.

How do you check if a string contains alphabets?

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.

How do you check if a string only contains letters in JS?

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.


1 Answers

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'; } 
like image 74
jb. Avatar answered Sep 22 '22 07:09

jb.