Search code examples
phpregexstringpreg-match

Validate a string as alphanumeric with some special character


I have check this link Validate username as alphanumeric with underscores.

I want to add more condition on string checking

My conditions;

Condition1: Alphanumeric including ! "#$%&'()*+,-./:;=?@^_~

How can do this in php help

Edit:

try with melwil answer

It show syntax error:

<?php

if (preg_match("//^[A-Za-z0-9_! "#$%&'()*+,\-.\\:\/;=?@^_]+$/", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Solution

  • Just add them:

    preg_match("/^[A-Za-z0-9_! \"#$%&'()*+,\-.\\:\/;=?@^_]+$/", "PHP is the web scripting language of choice.")
    

    Demo: https://regex101.com/r/sT9lG9/1

    Anything marked is legal. Be aware this does match space as well. If that was a mistake, just remove the space.