Search code examples
phpregexwhitelist

PHP regex: How to whitelist alphanumeric characters?


Can anyone tell me why 1 (blacklist) does not throw an unexpected end error and 2 (white list) does? 1 is not filtering out all the special characters so I want to use a whitelist approach. The error I'm getting seems to be related to syntax but I cannot spot it. Thank you for helping to end my misery.

php

(1)
if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $posteduid))
{
$error = "You may not use special characters in your username";
}

(2)
if (!preg_match("#^[a-zA-Z0-9]+$#", $posteduid))
{
$error = "You may not use special characters in your username";
}

error message:

Parse error: syntax error, unexpected $end in /.../join.php on line 346

Solution

  • When you comment out this line

    if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $posteduid))
    

    using // it will still see the ?> and stops parsing PHP, resulting in an weird error. Just remove that part or use /* */-comments. There is nothing wrong with your code-sample on the white list.