whitness11 whitness11 - 7 months ago 31
PHP Question

regex preg_match not working to match uppercase alpha and numeric albumID

I need to validate that the albumID input is 2 uppercase letters and 3 numbers. I used http://regexr.com/ and also http://www.tutorialspoint.com/php/php_preg_match.htm to confirm that this

preg_match('/([A-Z]{2}[0-9]{3})/', $albumid)


should work, but it's not:

<?php
// define variables and set to empty values
$albumidErr = $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (preg_match('/([A-Z]{2}[0-9]{3})/', $albumid))
{
$albumid = test_input($_POST["albumid"]);
$albumidErr = print $albumid;
}
else {
$albumidErr = " Album ID must be 2 Uppercase letters and 3 numbers (i.e. BI010)";
}

}
?>
<form method="post" action="
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>
<label for="albumid">*Album ID:</label>
<?php echo $albumidErr;?><br>
<input type="text" name="albumid" id="albumid"/>
</p>

<p>
<input type="submit" name="submit" id="submit" value="submit"/>
</p>
</form>

Answer

In your code:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/([A-Z]{2}[0-9]{3})/', $albumid))

you're making $albumid empty then you're trying to match the regex with this empty string, of course, it doesn't match.

I guess you want:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/([A-Z]{2}[0-9]{3})/', $_POST["albumid"]))
    //                                     ^^^^^^^^^^^^^^^^^

and you can add anchors:

$albumidErr =  $albumid = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (preg_match('/^([A-Z]{2}[0-9]{3})$/', $_POST["albumid"]))