How can I restrict some special characters only in PHP?

16,306

Solution 1

You should use:

([%\$#\*]+)

to match those characters.

So in preg_match you should use:

if(preg_match("/([%\$#\*]+)/", $firstname))
{
   echo 'Invalid Name';
}
else
{
   echo $firstname;
}

Solution 2

Blacklisting (=enumerating invalid characters) is not an option in the unicode world. Consider for example, a "name" like this:

Ж☝ⓚƒ

You don't really want to blacklist all of these.

A whitelisting approach is, on the contrary, quite simple using the u mode and unicode properties:

var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'ßäßå'));  // 1
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'r2d2'));  // 1
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'w#t?'));  // 0
var_dump(preg_match('/^[\p{L}\p{N}]+$/u', 'Ж☝ⓚƒ'));  // 0

And since we're talking about validating real names, please read Falsehoods Programmers Believe About Names before you start complicating things.

Share:
16,306
PNG
Author by

PNG

Updated on June 04, 2022

Comments

  • PNG
    PNG almost 2 years

    I am using preg_match for restrict the special characters in form post. Now I need to restrict some special characters only like %,$,#,* and I need to post like . How to possible to restrict some special characters only.

    My code:

    <?php
    $firstname='';
    if(isset($_POST['submit']))
    {
        $firstname=$_POST['firstname'];
        if(preg_match("/[^a-zA-Z0-9]+/", $firstname))
        {
        echo 'Invalid Name';
        }
        else
        {
        echo $firstname;
        }
    
    }
    ?>
    
    <html>
    <body>
    <form method="post">
    <input type="text" name="firstname"/>
    <input type="submit" name="submit" value="Submit"/>
    </form>
    </body>
    </html>
    
  • Toto
    Toto over 9 years
    You could add some punctuations like ' or - for O'Connors or Jean-François
  • georg
    georg over 9 years
    So, (^_^;) is a valid name?
  • georg
    georg over 9 years
    @M42: the linked article is quite helpful and entertaining - read it!
  • Toto
    Toto over 9 years
    Sure, I've already read it, I just said it may have punctuation in name.
  • Marcin Nabiałek
    Marcin Nabiałek over 9 years
    @georg Of course not, but OP wanted only restrict selected characters
  • georg
    georg over 9 years
    @M42: I understand. The thing is, if we start adding punctation, we should do this correctly (to disallow things like O'O'Connor) and then our assumptions about the structure will turn out wrong (they will do), and this is a never-ending story. There's no algorithm to validate every possible human name.
  • georg
    georg over 9 years
    Look, your code is quite different from what the OP has, because he (correctly) whitelists, and you blacklist. Blacklisting never works.