Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether every character is alpha-numeric in PHP?

Tags:

string

php

preg_match_all("/[^A-Za-z0-9]/",$new_password,$out);

The above only checks the 1st character, how to check whether all are alpha-numeric?

like image 774
wamp Avatar asked Jul 02 '10 03:07

wamp


People also ask

How do you know if a character is alpha numeric?

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space)!

How do you check if a character is a letter in PHP?

PHP | ctype_alpha() (Checks for alphabetic value) A ctype_alpha() function in PHP used to check all characters of a given string are alphabetic or not. If all characters are alphabetic then return True otherwise return False.

How many alpha numeric characters are there?

In layouts designed for English language users, alphanumeric characters are those comprised of the combined set of the 26 alphabetic characters, A to Z, and the 10 Arabic numerals, 0 to 9.


2 Answers

It's probably a better idea to use the builtin functions: ctype_alnum

like image 180
Jani Hartikainen Avatar answered Oct 11 '22 20:10

Jani Hartikainen


preg_match("/^[A-Za-z0-9]*$/", $new_password);

This gives true if all characters are alphanumeric (but beware of non-english characters). ^ marks the start of the string, and ^$^ marks the end. It also gives true if the string is empty. If you require that the string not be empty, you can use the + quantifier instead of *:

preg_match("/^[A-Za-z0-9]+$/", $new_password);
like image 28
Artefacto Avatar answered Oct 11 '22 21:10

Artefacto