Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 903
Lee Price Avatar asked Oct 13 '11 11:10

Lee Price


People also ask

What does Preg_match return in PHP?

The preg_match() function returns whether a match was found in a string.

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

What is alphanumeric in PHP?

A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.


2 Answers

Code:

if(preg_match('/[^a-z_\-0-9]/i', $string)) {   echo "not valid string"; } 

Explanation:

  • [] => character class definition
  • ^ => negate the class
  • a-z => chars from 'a' to 'z'
  • _ => underscore
  • - => hyphen '-' (You need to escape it)
  • 0-9 => numbers (from zero to nine)

The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z

like image 105
SERPRO Avatar answered Sep 24 '22 11:09

SERPRO


if(!preg_match('/^[\w-]+$/', $string1)) {    echo "String 1 not acceptable acceptable";    // String2 acceptable } 
like image 33
matino Avatar answered Sep 24 '22 11:09

matino