Reputation: 49
I want to match letters and numbers, but not only numbers.
So I want to create a preg_match()
pattern to filter like this:
eg:
no123
true 123no
true123456
falseletters
trueUpvotes: 1
Views: 216
Reputation: 47864
Using a SKIP-FAIL pattern will outperform Toto's pattern (and MH2K9's answer is incorrect as it doesn't allow all alphabetical matches). You can test their patterns on the sample text in my demo link.
/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i
This "disqualifies" purely numeric strings, and matches mixed (numeric-alphabetical) and purely alphabetical strings.
Code: (Demo)
$string='test123';
var_export(preg_match('/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i',$string)?true:false);
Output:
true
UPDATE: Regular expressions aside, this task logic can be performed by two very simple non-regex calls: ctype_alnum() and ctype_digit()
Code: (Demo)
$tests = [
'no123', // true
'123no', // true
'123456', // false
'letters', // true
];
foreach ($tests as $test) {
echo "$test evaluates as " , (ctype_alnum($test) && !ctype_digit($test) ? 'true' : 'false') , "\n";
}
Output:
no123 evaluates as true
123no evaluates as true
123456 evaluates as false
letters evaluates as true
Upvotes: 1
Reputation: 18490
So we must have at least one letter. There can be any amount of digits before it and any amount of alphanumeric characters is allowed until end of the string.
/^\d*[a-z][a-z\d]*$/i
^
start of string\d*
any amount of digits[a-z]
one letter[a-z\d]*
any amount of alphanumeric characters$
until end of the stringi
flag for caseless matchingUpvotes: 1
Reputation: 91385
According to your comment: "only letters vaild but only number invalid.", this wil do the job:
if (preg_match('/^(?=.*[a-z])[a-z0-9]+$/i', $inputString)) {
// valid
} else {
// invalid
}
Explanation:
/ : regex delimiter
^ : start of string
(?=.*[a-z]) : lookahead, make sure we have at least one letter
[a-z0-9]+ : string contains only letters and numbers
$ : end of string
/i : regex delimiter + flag case insensitive
Upvotes: 0