PHP regular expression to allow alphanumerics plus hyphens and periods
I really don't understand regular expressions and was wondering what the following regular expressions do. I want my address and name to accept .
, -
and alphanumerics.
Will this work or is there need for improvement? Plus if someone can break down the regular expressions '/^[A-Z0-9 \'.-]{1,255}$/i'
so I can understand every part better.
Here is the php co开发者_如何学运维de.
if (preg_match ('/^[A-Z0-9 \'.-]{1,255}$/i', $_POST['address'])) {
$address = mysqli_real_escape_string($mysqli, htmlentities($_POST['address']));
} else {
echo '<p class="error">Please enter your address!</p>';
}
if (preg_match ('/^[A-Z0-9 \'.-]{1,255}$/i', $_POST['name'])) {
$name = mysqli_real_escape_string($mysqli, htmlentities($_POST['name']));
} else {
echo '<p class="error">Please enter your name!</p>';
}
/
: Regex delimiter
^
: Anchor the match at the start of the string
[A-Z0-9 \'.-]
: Match a letter (A-Z, no accented characters), a number, a space, an apostrophe, a dot or a dash
{1,255}
: between 1 and 255 times.
$
: Anchor the match at the end of the string. Together with ^
, this ensures that the entire string must match, and not just a substring.
/
: Regex delimiter
i
: Make the regex case-insensitive
Your pattern basically allowes any combination (between 1 and 255 characters) of the following: A-Z, 0-9, space, \, ', .
Decide for yourself if this is good enough.
As for your pattern:
/^[A-Z0-9 \'.-]{1,255}$/i
The i at the end means it isnt case sensitive
/^[A-Z0-9 \'.-]{1,255}$/
The slashes denote the beginning and the end of the pattern
^[A-Z0-9 \'.-]{1,255}$
The ^ is the beginning and $ is the end of the string you look for
[A-Z0-9 \'.-]{1,255}
This allowes and combination of the characters between the brackets with 1 to 255 repetitions
精彩评论