tags:

views:

55

answers:

2

I really don't understand regular expressions and was wondering what the following regular expressions do I wanted my address and name to except periods hyphens letter uppercase and lowercase and numbers.

Is my regular expressions living up to there job and is there need for improvement? Plus if some one can break down the regular expressions '/^[A-Z0-9 \'.-]{1,255}$/i' so I can understand every part better. Thanks

Here is the php code.

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>';
}
A: 

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

Fabian
+1  A: 

/: 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

Tim Pietzcker