How to validate letter & number or only letter strings? - php

I want to match letters and numbers, but not only numbers.
So I want to create a preg_match() pattern to filter like this:
eg:
no123 true
123no true
123456 false
letters true

So we must have at least one letter. There can be any amount of digits before it and any amount of alphanumeric characters is allowed until end of the string.
/^\d*[a-z][a-z\d]*$/i
^ start of string
\d* any amount of digits
[a-z] one letter
[a-z\d]* any amount of alphanumeric characters
$ until end of the string
i flag for caseless matching
See this demo at regex101

Using a SKIP-FAIL pattern will outperform Toto's pattern (and MH2K9's answer is incorrect as it doesn't allow all alphabetical matches). You can test their patterns on the sample text in my demo link.
/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i
Pattern Demo Link
This "disqualifies" purely numeric strings, and matches mixed (numeric-alphabetical) and purely alphabetical strings.
Code: (Demo)
$string='test123';
var_export(preg_match('/^\d+$(*SKIP)(*FAIL)|^[a-z\d]+$/i',$string)?true:false);
Output:
true
UPDATE: Regular expressions aside, this task logic can be performed by two very simple non-regex calls: ctype_alnum() and ctype_digit()
Code: (Demo)
$tests = [
'no123', // true
'123no', // true
'123456', // false
'letters', // true
];
foreach ($tests as $test) {
echo "$test evaluates as " , (ctype_alnum($test) && !ctype_digit($test) ? 'true' : 'false') , "\n";
}
Output:
no123 evaluates as true
123no evaluates as true
123456 evaluates as false
letters evaluates as true

You can try this Regex. It checks both number and letter at least one.
(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$

According to your comment: "only letters vaild but only number invalid.", this wil do the job:
if (preg_match('/^(?=.*[a-z])[a-z0-9]+$/i', $inputString)) {
// valid
} else {
// invalid
}
Explanation:
/ : regex delimiter
^ : start of string
(?=.*[a-z]) : lookahead, make sure we have at least one letter
[a-z0-9]+ : string contains only letters and numbers
$ : end of string
/i : regex delimiter + flag case insensitive

Related

My regex correctly doesn't accept a string online, but preg_match() returns true

I have this regular expression /^(string#)([^#\s\\\\]|(\\\d{3}))*$/.
It's supposed to accept strings that start with string#, then all characters but #, \, or any whitespace characters can follow. \ can only appear when it's followed by 3 digits.
When I test this regex with the string string#test\07test on regex101.com and phpliveregex.com, no matches are found (correctly), but preg_match() returns true for the same string.
What am I doing wrong?
Thank you
UPDATE:
$regex = "/^(string#)([^#\s\\\\]|(\\\d{3}))*$/";
preg_match($regex, 'string#test\07test'); # this returns false, as it should
preg_match($regex, "string#test\07test"); # this returns true
The test string is taken from a file using fgets() and stored in a variable, though, so I can't pass it to preg_match() and put apostrophes around it, I need to pass the variable ($string, for example), and preg_match($regex, $string) incorrectly returns true again.
First things first:
'\07' is a string of length 3 beginning with a backslash character.
"\07" is a string of length 1 consisting of ASCII x'07'
Interactive shell
php > echo strlen('\07');
3
php > echo strlen("\07");
1
php >
See PHP Strings
Regex:
/^string#(?:[^#\s\\]|\\(?=\d{3}))*$/
See Regex Demo
^ Matches start of string.
string# Matches string#.
[^#\s\\] Matches any character other than #, white space or \.
| or
\\(?=\d{3}) Matches \ if followed by 3 digits.
(?: expression 3 through 5)* matched 0 or more times.
$ Matches the end of string.
Code:
<?php
$tests = [
'abcd',
'string# test',
'string##test',
'string#\07test',
'string#\075test',
'string#test'
];
$regex = '/^string#(?:[^#\s\\\\]|\\\\(?=\d{3}))*$/';
foreach ($tests as $test) {
if (preg_match($regex, $test)) {
echo "$test\n";
}
}
Prints:
string#\075test
string#test

Ensure a string contains specific characters, each at most once

I would like to test if a string is empty or if it only contain specific characters, each at most once.
Example:
Given $valid = 'ABCDE', the following strings are:
$a = ''; // valid, empty
$b = 'CE'; // valid, only contains C and E, each once
$c = 'AZ'; // invalid, contains Z
$d = 'DAA'; // invalid, contains A twice
Any quick way of doing this, (possibly) using regex?
We can try using the following regex pattern:
^(?!.*(.).*\1)[ABCDE]{0,5}$
Here is an explanation of the regex:
^ from the start of the string
(?!.*(.).*\1) assert that the same letter does not repeat
[ABCDE]{0,5} then match 0-5 letters
$ end of the string
Sample PHP script:
$input = "ABCDE";
if (preg_match("/^(?!.*(.).*\1)[ABCDE]{0,5}$/", $input)) {
echo "MATCH";
}
The negative lookahead (?!.*(.).*\1) works by checking if it can capture any single letter, and then also find it again later on in the string. Let's take the OP's invalid input DAA. The above negative lookahead would ffail when it matches and captures the first A, and then sees it again. Note carefully that lookarounds can have their own capture groups.

How to get right result of preg_match() in this case

I want to get result from preg_match() in this case.
$regex = '/[A-Z][a-z][0-9]/i';
What is the right code to get result below.
preg_match($regex, 'phpversion7') //return false
preg_match($regex, 'Phpversion7') //return true
preg_match($regex, 'Phpversion') //return false
preg_match($regex, 'R1985y2528') //return true
preg_match($regex, 'R19852528') //return false
Simple asign a variable to each preg_match () statement which will store a boolean
Not very clear what you want, but I guess you need something like:
/^[A-Z](?=.*[a-z])(?=.*\d)[a-zA-Z\d]+$/
This regex matches strings that begin with a capital letter and contain at least one letter and at leat one digit.
Explanation:
/ : regex delimiter
^ : start of string
[A-Z] : a capital letter
(?=.*[a-z]) : lookahead, a small letter must be present in the string
(?=.*\d) : lookahead, a digit must be present in the string
[a-zA-Z\d]+ : the whole string must contains only letters and digits.
$ : end of string
/ : regex delimiter

PHP check if string contains maximum 30 letters/numbers in a sequence with preg_match

I'm stuck here and I can't find any results for my question, maybe because english is not my native language.
I want to match lines which contain maximum 30 letters/numbers in a sequence:
Is this even possible with preg_match?
preg_match("/[^A-Za-z0-9](max 30 in a sequence)/", $string)
Strings:
$string = "1234567890123456789012345678901234567890"; // FALSE
$string = "sdfihsgbfsadiousdghiug"; // TRUE
$string = "cfgvsdfsdf786sdf78s9d8g7stdg87stdg78tsd7g0tsd9g7t"; // FALSE
$string = "65656.sdfsdf.sdfsdf"; // TRUE
$string = "ewrwet_t876534875634875687te8---7r9w358wt3587tw3587"; // TRUE
$string = "sd879dtg87dftg87dftg87ftg87tfg087tfgtdf8g7tdf87gt8t___454"; // FALSE
You might want to find if there's 30 or more of these characters with:
preg_match("/[A-Za-z0-9]{30,}/", $string)
See matches in bold:
1234567890123456789012345678901234567890
sdfihsgbfsadiousdghiug
cfgvsdfsdf786sdf78s9d8g7stdg87stdg78tsd7g0tsd9g7t
65656.sdfsdf.sdfsdf
ewrwet_t876534875634875687te8---7r9w358wt3587tw3587
sd879dtg87dftg87dftg87ftg87tfg087tfgtdf8g7tdf87gt8t___454
http://regexr.com/3arj2
And then negate the result:
preg_match("/[A-Za-z0-9]{30,}/", $string) === 0
// returns 0 if no match
// or FALSE if error
If you do not want to match alphanumeric strings that are longer than 30 characters, you need to match a non-alphanumeric character at the end and beginning of your expression
preg_match("/[^A-Za-z0-9][A-Za-z0-9]{1,30}[^A-Za-z0-9]/", $string);
Non of your examples will match, your regex is incorrect. You need the ^ outside of the character class, inside it means exclude. If nothing entered is valid this should work. If not change the 0 to a 1.
preg_match("/^[A-Za-z0-9]{0,30}/", $string)

modify values in variable string with php

Consider example:
$mystring = "us100ch121jp23uk12";
I) I want to change value of jp by adding +1 so that makes the string into
us100ch121jp24uk12
suppose if
II) Is there a way to seperate the numeric part and alphabetic part in the above string into:
[us , 100]
[ch,121]
[jp,24]
[us,12]
my code:
$string = "us100ch121jp23uk12";
$search_for = "us";
$pairs = explode("[]", $string); // I dont know the parameters.
foreach ($pairs as $index=>$pair)
{
$numbers = explode(',',$pair);
if ($numbers[0] == $search_for){
$numbers[1] += 1; // 23 + 1 = 24
$pairs[index] = implode(',',$numbers); //push them back
break;
}
}
$new_string = implode('|',$pairs);
using Evan sir's suggestions
$mystring = "us100ch121jp22uk12";
preg_match_all("/([A-z]+)(\d+)/", $mystring, $output);
//echo $output[0][4];
foreach($output[0] as $key=>$value) {
// echo "[".$value."]";
echo "[".substr($value, 0, 2).",".substr($value, 2, strlen($value) - 2)."]"."<br>";
}
If you use preg_match_all("/([A-z]+)(\d+)/", $string, $output);, it will return an array to $output that contains three arrays. The first array will be country number strings (eg 'us100'). The second will contain country strings (eg 'us'). The third will contain the numbers (eg '100').
Since the second and third arrays will have matching indexes ($output[1][0] will be 'us' and $output[2][0] will be '100'), you could just cycle through those and do whatever you'd like to them.
Here is more information about using regular expressions in PHP. The site also contains information about regular expressions in general, which are a useful tool for any programmer!
You can do it using regular expressions in PHP. See tutorial:
http://w3school.in/w3schools-php-tutorial/php-regular-expression/
Function Description
ereg_replace() The ereg_replace() function finds for string specified by pattern and replaces pattern with replacement if found.
eregi_replace() The eregi_replace() function works similar to ereg_replace(), except that the search for pattern in string is not case sensitive.
preg_replace() The preg_replace() function works similar to ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_match() The preg_match() function finds string of a pattern and returns true if pattern matches false otherwise.
Expression Description
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
[A-Z] It matches any character from uppercase A through uppercase Z.
[a-Z] It matches any character from lowercase a through uppercase Z.
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p’s.
p? It matches any string containing zero or more p’s. This is just an alternative way to use p*.
p{N} It matches any string containing a sequence of N p’s
p{2,3} It matches any string containing a sequence of two or three p’s.
p{2, } It matches any string containing a sequence of at least two p’s.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z.
p.p It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$ It matches any string containing exactly two characters.
<b>(.*)</b> It matches any string enclosed within <b> and </b>.
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
you also can use JavaScript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Categories