Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...