[php] PHP preg_match - only allow alphanumeric strings and - _ characters

I need the regex to check if a string only contains numbers, letters, hyphens or underscore

$string1 = "This is a string*";
$string2 = "this_is-a-string";

if(preg_match('******', $string1){
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

This question is related to php regex preg-match

The answer is


\w\- is probably the best but here just another alternative
Use [:alnum:]

if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";

demo1 | demo2


Here is one equivalent of the accepted answer for the UTF-8 world.

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.


if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

Why to use regex? PHP has some built in functionality to do that

<?php
    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";
    }
?>

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to preg-match

Preg_match backtrack error Regular expression containing one word or another How to search in an array with preg_match? PHP preg_match - only allow alphanumeric strings and - _ characters Delimiter must not be alphanumeric or backslash and preg_match PHP is_numeric or preg_match 0-9 validation Regex: Specify "space or start of string" and "space or end of string" PHP regular expressions: No ending delimiter '^' found in PHP - regex to allow letters and numbers only