Tom
Tom

Reputation: 81

PHP regular expression numeric plus one letter

I'm trying to achieve validation for numeric input plus letter X or x. So far I have:

if(preg_match('/[^0-9xX]+$/', $data)) return 'error';

It correctly returns error for all cases EXCEPT a123. Have anyone idea why?

Upvotes: 0

Views: 155

Answers (4)

Tushar
Tushar

Reputation: 87203

Use ^ at the start of regex to check if the complete string instead of sub-string.

if(preg_match('/^[0-9xX]+$/', $data))
    return 'error';

Upvotes: 1

Fake Face
Fake Face

Reputation: 116

I don't got it.

if(preg_match('/^[0-9xX]+$/', $data)) return 'error';

still doesn't return error when we enter 123.

I'm sorry if i make misunderstanding.

if(preg_match('/[0-9]xX$/', $data)) return 'error';

All number will be followed by xX. CMIIW.

Upvotes: 0

Kerwin
Kerwin

Reputation: 1212

if(!preg_match('/^([0-9]+|[xX])$/', $data)) return 'error';

Maybe this would be better, it match the right case,and add ! before match result.

Upvotes: 0

Bernhard
Bernhard

Reputation: 1870

Try this:

if(preg_match('/^[0-9x]+$/i', $data)){
 echo 'match';
}else{
 echo 'no match';
}

Its like yours, only the other way round. ^ is for the begin of the string. $ For the end of the string. So the whole string must match the pattern.

Upvotes: 0

Related Questions