Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

php - Check if a string contains numbers and letters

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...