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 }
The preg_match() function returns whether a match was found in a string.
The preg_match() function will tell you whether a string contains matches of a pattern.
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.
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.
Code:
if(preg_match('/[^a-z_\-0-9]/i', $string)) { echo "not valid string"; }
Explanation:
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
if(!preg_match('/^[\w-]+$/', $string1)) { echo "String 1 not acceptable acceptable"; // String2 acceptable }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With