Skip to content
Advertisement

How can I restrict some special characters only in PHP?

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>

Advertisement

Answer

You should use:

([%$#*]+)

to match those characters.

So in preg_match you should use:

if(preg_match("/([%$#*]+)/", $firstname))
{
   echo 'Invalid Name';
}
else
{
   echo $firstname;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement