Php function to determine if a string consist of only alphanumerical characters? - php

Is there a Php function to determine if a string consist of only ASCII alphanumerical characters?
Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual.

Try ctype_alnum

preg_match('/^[a-z0-9]+$/i', $str);
Edit: John T's answer is better. Just providing another method.

This is my solution
<?php
public function alphanum($string){
if(function_exists('ctype_alnum')){
$return = ctype_alnum($string);
}else{
$return = preg_match('/^[a-z0-9]+$/i', $string) > 0;
}
return $return;
}
?>

My long, but simple solution
strspn($string, '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_') == strlen($string)
Function strspn() finds the length of the initial segment of $string that contains only letters, numbers and underscore character (second argument). If entire string consists only of letters, numbers and underscore, the returned value will be equeal to the length of the string.

Related

PHP - Password RegEx requirements

I am trying to validate if a new user account's password is matching these criterias:
Between 8-30 characters long
Contains at least 1 lowercase letter (a-z)
Contains at least 1 uppercase letter (A-Z)
Contains at least 1 of the following special characters: _-!#*#&
I have a function like this:
function validPassword($str) {
return preg_match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_-!#*#&])[A-Za-z\d_-!#*#&]{8,30}$", $str);
}
But I am getting an error. It should return "true" for this password for example: HelloWorld123!
But instead it is returning false. Any idea what may be wrong?
if (validPassword($password) == true) {
// good password
}
You forgot to escape '-', and delimiters...
function validPassword($str) {
return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$/", $str);
}
Your regex is having errors which is why there is no match in the first place.
Change your regex to this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$
Have a look at your regex in action here: https://regex101.com/r/ogPPeb/1

Function to check if the first character of a string is a letter

I made this function to check if the first character is a letter.
function isLetter($string) {
return preg_match('/^\s*[a-z,A-Z]/', $string) > 0;
}
However, if I check a sentence that starts with a coma (,) the functions returns true. What is the proper regex to check if the first letter is a-z or A-Z?
You just need to remove the comma:
'/^\s*[a-zA-Z]/'
A slightly cleaner way, in my opinion. Just makes the code a little more human readable.
function isLetter($string) {
return preg_match('/^[a-z]/i', trim($string));
}

Function to count number of digits in string

I was looking for a quick PHP function that, given a string, would count the number of numerical characters (i.e. digits) in that string. I couldn't find one, is there a function to do this?
This can easily be accomplished with a regular expression.
function countDigits( $str )
{
return preg_match_all( "/[0-9]/", $str );
}
The function will return the amount of times the pattern was found, which in this case is any digit.
first split your string, next filter the result to only include numeric chars and then simply count the resulting elements.
<?php
$text="12aap33";
print count(array_filter(str_split($text),'is_numeric'));
edit: added a benchmark
out of curiosity: (loop of 1000000 of above string and routines)
preg_based.php is overv's preg_match_all solution
harald#Midians_Gate:~$ time php filter_based.php
real 0m20.147s
user 0m15.545s
sys 0m3.956s
harald#Midians_Gate:~$ time php preg_based.php
real 0m9.832s
user 0m8.313s
sys 0m1.224s
the regular expression is clearly superior. :)
For PHP < 5.4:
function countDigits( $str )
{
return count(preg_grep('~^[0-9]$~', str_split($str)));
}
This function goes through the given string and checks each character to see if it is numeric. If it is, it increments the number of digits, then returns it at the end.
function countDigits($str) {
$noDigits=0;
for ($i=0;$i<strlen($str);$i++) {
if (is_numeric($str{$i})) $noDigits++;
}
return $noDigits;
}

Regex to validate only natural numbers?

I recently found out that a method I've been using for validating user input accepts some values I'm not particularly happy with. I need it to only accept natural numbers (1, 2, 3, etc.) without non-digit characters.
My method looks like this:
function is_natural($str)
{
return preg_match('/[^0-9]+$/', $str) ? false : $str;
}
So it's supposed to return false if it finds anything else but a whole natural number. Problem is, it accepts strings like "2.3" and even "2.3,2.2"
perhaps you can clarify the difference between a "number" and a "digit" ??
Anyways, you can use
if (preg_match('/^[0-9]+$/', $str)) {
// contains only 0-9
} else {
// contains other stuff
}
or you can use
$str = (string) $str;
ctype_digit($str);
The problem with /^[0-9]+$/ is that it also accepts values like 0123.
The correct regular expression is /^[1-9][0-9]*$/.
ctype_digit() suffers the same problem.
If you also need to include zero use this regex instead: /^(?:0|[1-9][0-9]*)$/
Use ctype_digit() instead
I got an issue with ctype_digit when invoice numbers like "000000196" had to go through ctype_digit.
So I have used a:
if (preg_match('/^[1-9][0-9]?$/', $str)) {
// only integers
} else {
// string
}

How to check whether every character is alpha-numeric in 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?
It's probably a better idea to use the builtin functions: ctype_alnum
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);
Old question, but this is my solution:
<?php
public function alphanum($string){
if(function_exists('ctype_alnum')){
$return = ctype_alnum($string);
}else{
$return = preg_match('/^[a-z0-9]+$/i', $string) > 0;
}
return $return;
}
?>

Categories