We're going to take a break from math-related functions for a few weeks (yay!) and play with regular expressions. Regular expressions are more powerful and faster than old-fashioned string parsing.
Both ASP and PHP have a function for checking if something is numeric. How about a function for checking if something is alphabetical?
ASP
function isAlpha(someString)
dim regEx
set regEx = new RegExp
with regEx
.Global = true
.IgnoreCase = true
.Pattern = "[A-Z\s_]"
end with
if regEx.test(someString) then
isAlpha = true
else
isAlpha = false
end if
set regEx = nothing
end function
PHP
function is_alpha($someString)
{
return (preg_match("/[A-Z\s_]/i", $someString) > 0) ? true : false;
}
The test pattern we are using above will allow letters of the alphabet, the underscore character, and whitespace characters. With a small tweak to the test pattern, we can also write a function to check if a string is alphanumeric.
ASP
function isAlphaNumeric(someString)
dim regEx
set regEx = new RegExp
with regEx
.Global = true
.IgnoreCase = true
.Pattern = "[\w\s.]"
end with
if regEx.test(someString) then
isAlphaNumeric = true
else
isAlphaNumeric = false
end if
set regEx = nothing
end function
PHP
function is_alphanumeric($someString)
{
return (preg_match("/[\w\s.]/i", $someString) > 0) ? true : false;
}
The \w switch in the pattern includes the 26 letters of the alphabet plus the numbers zero through nine.
More regular expression fun next week!
2 comments:
I assume the PHP isAlpha() function is supposed to mirror the built-in is_numeric() function. However, it does not, because it allows numeric characters. For example take the string "234kol". The is_numeric() function will return FALSE because while the string does contain numbers, it also contains characters. However, your isAlpha() function will return TRUE, ignoring the fact that the string contains numbers. It is a subtle but important distinction.
Interesting. I tried to do some testing in PHP but my web server is not behaving itself. I switched to a piece of regular expression software and was able to get the expected result with the following pattern: ^[A-Z\s_]+$
I'm hesitant to update my original code without proper testing in PHP though.
Post a Comment