hello,
how do i check a field contain number and alphabet.
something like $str = 3ab, ab3, a3
hello,
how do i check a field contain number and alphabet.
something like $str = 3ab, ab3, a3
To check if a string contains number and alphabet you can do, write a small regex based function as:
function contains_num_alpha($str) {
return preg_match('/^[a-z0-9]+$/i',$str);
}
The regex used: ^[a-z0-9]+$
^, $ - anchors[a-z0-9] - char class that matches a
single digit or a single alphabet.[a-z0-9]+ - one or more
digits/alphabets.i - to make the matching case
insensitive.If you want to allow even empty string, you can change + to * in the regex.
You can use regex
$stringGood = 'abc2';
$stringBad = '2#2(7X%';
function isValidAlphaNum($str) {
return preg_match('/^[a-z\d]+$/i', $str);
}
var_dump(validateAlphaNum($stringGood)); // true
var_dump(validateAlphaNum($stringBad)); // false
If you wanted to allow uppercase and lowercase alphabetical characters, numbers and underscore you can use this regex: /^\w+$/
Not sure of what you're asking, but if you want to check whether a string has at least 1 alpha and 1 numeric character in it, then this regular expression ought to do it:
<?php
if (preg_match("^[a-zA-Z0-9]{1,}$", $str) {
// match was found;
}
?>
<?php
if (is_string("23")) {
echo "is string\n";
} else {
echo "is not an string\n";
}
var_dump(is_string('abc'));
var_dump(is_string("23"));
var_dump(is_string(23.5));
var_dump(is_string(true));
?>
Use the is_string function. Returns TRUE if the argument type is string , FALSE otherwise.
<?php
$tests = Array(
"42",
1337,
"1e4",
"not numeric",
Array(),
9.1
);
foreach($tests as $element)
{
if(is_numeric($element))
{
echo "'{$element}' is numeric", PHP_EOL;
}
else
{
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
If you want to check the input is numeric use the "is_numeric" function
It return true, if the argument is numeric. Else it return false