how to check if a variable contains both numbers and letters ? for example abcd1234 and how to split numbers from letters in this example ?
Could do: $numtest = NULL; $lettertest = NULL; $array1 = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); $array2 = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); $numtest = substr_count($string, $array1); $lettertest = substr_count($string, $array2); if($numtest == NULL || $lettertest == NULL){ You're missing either a number or a letter. } Not sure if there's a btter way, not had to do that before.
The following will test and extract the numbers: <?php $in = 'abcd1234'; $r = array(); if(preg_match('/^[a-z]+(\d+)$/', $in, $r)) { echo "The numbers are $r[1]"; } else echo "String missing numbers or letters"; ?> PHP: However I've based that on your example and so have assumed that the string always starts with 1 or more lowercase letters and ends with 1 or more numbers, any other pattern of letters and numbers will fail to match. If you have other patterns of letters and numbers then you'll need to show me them all so I can change that.
This will match if your string contains any upper/lowercase letter and a digit if (preg_match('/([a-z].*?[0-9]|[0-9].*?[a-z])/i', $input)) { # Successful match } else { # Match attempt failed } PHP:
How about that <?php $subject = '1234abcd5678efgh'; $result = preg_split('/([0-9]+)|([a-z]+)/si', $subject, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); print_r($result); PHP:
Kind of depends on the input pattern doesn't it, if all the input is in the same form as the example then a test and extract would seem the optimal solution. If the pattern is fixed as in the example then a preg_match will verify that the input is indeed in that form while ctype_alnum will not, so depending on where this is in the code, that is if this is data from a user or data a user can tamper with then a more strict type checking will limit or avoid issues with incorrectly input data and may increase security of the script. All boils down to what's expected and where the data comes from.
Mate, consider the result array is empty. Then no letters or digits where present at the string. That is exactly what he needs. Read post #1 again.
It won't be empty if there's digits only or letters only, he asked "how to check if a variable contains both numbers and letters ?", therefore while what you have extracts the data nicely it doesn't test that both letters and numbers are present, you'd need an additional check.