How to check whether every character is alpha-numeric in PHP? - 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;
}
?>

Related

Check input contains either pure numeric characters or pure alpha character using single regular expression

I have a function which will return true if input is pure numeric or alphabate else it will return false. This function is working fine.
function checktype($a)
{
if (preg_match('/^\d+$/', $a)) { //check numeric (can use other numeric regex also like /^[0-9]+$/ etc)
$return = true;
} else if (preg_match('/^[a-zA-Z]+$/', $a)) { //check alphabates
$return = true;
} else { //others
$return = false;
}
return $return;
}
var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)
No I tried to optimized this function by removing conditions so I modified code to:
function checktype($a)
{
$return = (preg_match('/^\d+$/', $a) || preg_match('/^[a-zA-Z]+$/', $a)) ? true:false;
return $return;
}
var_dump(checktype('abcdfekjh')); //bool(true)
var_dump(checktype('1324654')); //bool(true)
var_dump(checktype('1324654hkjhkjh'));//bool(false)
Now in third step I tried to merge both regex in single regex so I can avoid two preg_match function and got stuck here:
function checktype($a)
{
return (preg_match('regex to check either numeric or alphabates', $a)) ? true:false;
}
I tried a lot of combinations since 2 days by using OR(!) operator using not operator(?!) but no success at all.
Below some reference website from which i pick expression and made some combinations:
http://regexlib.com/UserPatterns.aspx?authorid=26c277f9-61b2-4bf5-bb70-106880138842
http://www.rexegg.com/regex-conditionals.html
OR condition in Regex
Regex not operator (come to know about NOT operator)
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regular+expression+not+condition (come to know about NOT operator)
So here main question is, is there any single regex pattern to check string contains pure numeric value or pure alphabates?
Note: Alternative solution can be check string is alphanumeric and then return true or false accordingly. Also php inbuilt function like is_numeric and is_string can be used, but I am more curious to know the single regex pattern to check weather string conains pure numeric digit or pure alphaba digits.
A one regex to check if a string is all ASCII digits or all ASCII letters is
'/^(?:\d+|[a-zA-Z]+)$/'
See regex demo
This regex has two things your regexps do not have:
a grouping construct (?:....)
an alternation operator |.
Explanation:
^ - start of string
(?:\d+ - one or more digits
| - or...
[a-zA-Z]+) - one or more ASCII letters
$ - end of string
If you need to make it Unicode-aware, use [\p{L}\p{M}] instead of [a-zA-Z] (and \p{N} instead of \d, but not necessary) and use the /u modifier:
'/^(?:\p{N}+|[\p{L}\p{M}]+)$/u'
And in case you want to really check that from the beginning to end, use
'/\A(?:\p{N}+|[\p{L}\p{M}]+)\z/u'
^^ ^^
or
'/^(?:\p{N}+|[\p{L}\p{M}]+)$/Du'
The $ without /D modifier does not match the string at its "very end", it also matches if there is a newline after it as the last character.

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));
}

Regex not working for password? not sure why

So I have a regex code to make sure the password is from 4 to 13 characters, it keeps failing
public function valid_password($password){
if(preg_match('^.{3,14}^', $password)){
return true;
}//end if
else{
return false;
}//end else
}
I'm using regex and not php's length attribute because I will be adding more regex code later on. However, now I'm stuck with this failing program.
The problem is, it makes sure the password is over 3 characters however it doesn't care how long it is as if I have set no limit.
Thanks in advance
You have used ^ as delimiters php.net/mregexp.reference.delimiters.php here:
^.{3,14}^
That's possible, but not a good idea in your case, because you need the ^ for its actual purpose. It matches the start of the subject normally. And to correctly count the length, yout need to do that. You also need the $ end of subject meta character.
So basically:
preg_match('/^.{3,14}$/'
Now if you want to combine this regex with other match criteria, I would recommend this fancy assertion syntax:
preg_match('/(?=^.{3,14}$) (...)/x', $password)
This will allow you to specify something else in place of ... - and keep the length check implicit.
^ is the anchor for the beginning of a string. The end of a string is delimited using $:
public function valid_password($password) {
return preg_match('~^.{3,14}$~', $password);
}
But in this case I wouldn't use a regex, but the strlen function instead:
public function valid_password($password) {
$length = strlen($password);
return $length >= 3 && $length <= 14;
}
If you like hacking around to save you that line:
public function valid_password($password) {
return isset($password[2]) && !isset($password[14]);
}
But really, why do you want to restrict password length to 14 characters? That way you prevent people from choosing really secure passwords. You probably should raise that limit.
Try this:
preg_match('/^.{3,14}$/', $password)
try
preg_match('/^.{3,14}$/', $password)
but regexp for counting string length?? = Overkill
^ matches the start of a string, not the end. $ matches the end.
And you forgot your delimiters.
The full, fixed line is:
if (preg_match('/^.{3,14}$/', $password)) {
However, I strongly recommend that you instead use:
$len = strlen($password);
if ($len >= 3 && $len <= 14) {
instead, since regular expressions are completely overkill for this.

Check if a String Ends with a Number in PHP

I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.
function endsWithNumber($string) {
$endsWithNumber = false;
// Logic
return $endsWithNumber;
}
return is_numeric(substr($string, -1, 1));
This only checks to see if the last character in the string is numerical, if you want to catch and return multidigit numbers, you might have to use a regex.
An appropriate regex would be /[0-9]+$/ which will grab a numerical string if it is at the end of a line.
$test="abc123";
//$test="abc123n";
$r = preg_match_all("/.*?(\d+)$/", $test, $matches);
//echo $r;
//print_r($matches);
if($r>0) {
echo $matches[count($matches)-1][0];
}
the regex is explained as follows:
.*? - this will take up all the characters in the string from the start up until a match for the subsequent part is also found.
(\d+)$ - this is one or more digits up until the end of the string, grouped.
without the ? in the first part, only the last digit will be matched in the second part because all digits before it would be taken up by the .*
To avoid potential undefined index error use
is_numeric($code[strlen($code) - 1])
instead.
in my opinion The simple way to find a string ends with number is
$string = "string1";
$length = strlen($string)-1;
if(is_numeric($string[$length]))
{
echo "String Ends with Number";
}
Firstly, Take the length of string, and check if it is equal to zero (empty) then return false. Secondly, check with built-in function on the last character $len-1.
is_numeric(var) returns boolean whether a variable is a numeric string or not.
function endsWithNumber($string){
$len = strlen($string);
if($len === 0){
return false;
}
return is_numeric($string[$len-1]);
}
Tests:
var_dump(endsWithNumber(""));
var_dump(endsWithNumber("str123"));
var_dump(endsWithNumber("123str"));
Results:
bool(false)
bool(true)
bool(false)
This should work
function startsWithNumber(string $input):bool
{
$out = false; //assume negative response, to avoid using else
if(strlen($input)) {
$out = is_numeric($input[0]); //only if string is not empty, do this to avoid index related errors.
}
return $out;
}

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

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.

Categories