[nycphp-talk] Reg expression to make sure something is not blank
David Sklar
sklar at sklar.com
Wed Sep 17 12:20:37 EDT 2003
On Wednesday, September 17, 2003 12:09 PM, wrote:
> Is this "kosher" for determining that something has not be left blank?
>
> '/^[^^$]{1,35}$/i',
No, it is not kosher. The regex matches strings like "country ham", "cheese
burger" and "shrimp scampi". In fact, it matches any 1 to 35 character
string that doesn't consist entirely of carets and dollar signs. If you want
to make sure that a string at least one but no more than 35 characters, use:
/^.{1,35}$/
But that would match a string of all whitespace. If you want to make sure
that the string doesn't begin with whitespace, try:
/^\S.{0,34}$/
Which guarantees that the first character is not whitespace.
However, you're better off not using a regex for this stuff. Instead, do
this to make sure a string is between 1 and 35 characters, after removing
leading and trailing whitespace:
$len = strlen(trim($s));
if (($len < 1) || ($len > 35)) {
// the string is too long or too short
} else {
// the string is just right
}
David
More information about the talk
mailing list