preg match for digits and alphabet - php

I'm making preg_match that allows 7-10 digits.
preg_match('/[0-9]{7,10}/', $studentID
Also another preg_match code that allows maximum of 20 alphabets with space and hyphen.
preg_match ('/^[a-zA-Z -]{,20}+$/i', $familyname
Both of these are not working.

You need to add anchors to the first regex the same way you used them with the second pattern, and you must define the lower bound for the limiting quantifier in the second pattern (say, 0 to 20):
$studentID = "1234567";
if (preg_match('/^[0-9]{7,10}$/', $studentID)) {
echo "$studentID matched!\n";
}
$familyname = "Pupkin";
if (preg_match ('/^[A-Z -]{0,20}$/i', $familyname)) {
echo "$familyname matched!";
}
See the PHP demo
Note that {0,20} and its possessive {0,20}+ version will work the same here since the pattern is not followed with other consuming subpatterns (so, no need to disable backtracking for the quantified subpattern).
Also, '/^[A-Z -]{0,20}$/i' is a very generic subpattern for surnames, you might want to further precise it. E.g., to disallow strings like all spaces or ---------, you may use '/^(?=.{0,20}$)[A-Z]+(?:[ -][A-Z]+)*$/i'.

Related

Finding presence of chars or strings out of the allowed ones

Well, I'm stuck, I cannot find the correct form for the RegEx to provide to the PHP preg_match.
I have two strings. Say "mdo" and "o", but they could be really random.
I have a dictionary of allowed chars and strings.
For the example, allowed chars are "a-gm0-9", and allowed strings are "do" and "si".
THE GOAL
I'm trying to check that the input string doesn't contain any char or string but those in the dictionary, case-insensitive.
So the case of "mdo" wouldn't match because m is allowed just like the string do. Not the same for o instead, which has o that is not an allowed char and which doesn't contain the whole allowed string do.
My struggling reason
It's ok to negate [^a-gm0-9] and (?!do|si), but what I cannot achieve is to place them inside a single regex in order to apply the following PHP code:
<?php
$inputStr = 'mdo';
$rex = '/?????/i'; // the question subject
// if disallowed chars/strings are found...
if( preg_match($regex, $inputStr) == 1 )
return false; // the $inputStr is not valid
return true;
?>
Because two cascading preg_matches would break the logic and don't work.
How to mix chars check and groups check in "AND" in a single regex? Their positions don't matter.
You can use this pattern:
return (bool) preg_match('~^(?:do|si|[a-gm0-9])*+\C~i', $inputStr);
The idea is to match all allowed chars and substrings from the start in a repeated group with a possessive quantifier and to check if a single byte \C remains. Since the quantifier is greedy and possessive, the single byte after, if found, can't be allowed.
Note that most of the time, it is more simple to negate the preg_match function, example:
return (bool) !preg_match('~^(?:do|si|[a-gm0-9])*$~iD', $inputStr);
(or with a + quantifier, if you don't want to allow empty strings)

Move multiple letters in string using regex

Using a regular expression I want to move two letters in a string.
W28
L36
W29-L32
Should be changed to:
28W
36L
29W-32L
The numbers vary between 25 and 44. The letters that need to be moved are always "W" and/or "L" and the "W" is always first when they both exist in the string.
I need to do this with a single regular expression using PHP. Any ideas would be awesome!
EDIT:
I'm new to regular expressions and tried a lot of things without success. The closest I came was using "/\b(W34)\b/" for each possibility. I also found something about using variables in the replace function but had no luck using these.
Your regex \b(W34)\b matches exactly W34 as a whole word. You need a character class to match W or L, and some alternatives to match the numeric range, and use the most of capturing groups.
You can use the following regex replacement:
$re = '/\b([WL])(2[5-9]|3[0-9]|4[0-4])\b/';
$str = "W28\nL36\nW29-L32";
$result = preg_replace($re, "$2$1", $str);
echo $result;
See IDEONE demo
Here, ([WL]) matches and captures either W or L into group 1, and (2[5-9]|3[0-9]|4[0-4]) matches integer numbers from 25 till 44 and captures into group 2. Backreferences are used to reverse the order of the groups in the replacement string.
And here is a regex demo in case you want to adjust it later.

perl regex match any number that is not

given a string:
//foo.bar/baz/123/index.html
I am trying to match the number after baz, so long as it is not 123.
//foo.bar/baz/124/index.html (WOULD MATCH)
//foo.bar/baz/123/index.html (WOULD NOT MATCH)
How can I express this? I keep trying things like:
/baz\/d+^(123)/index/
but have not been successful. Any help is appreciated!
Use negative look-ahead to assert that there is not 123 after baz/. Then go on to match with \d+:
m~baz/(?!123\b)\d+/index~
In Perl, you can use different delimiter when your regex pattern already contains /, to avoid escaping them. Here I've used ~.
If the substring to not allow is fixed to be baz/123, you can also do it with index() function:
$str = "//foo.bar/baz/124/index.html";
$needle = "/baz/123/";
if (index($str, $needle) == -1) {
print "Match found\n";
}

Php Sanitize and Validate form with some character exceptions

I'm using in Php Sanitize and Validate Filters but I have problems to add some rules, I have some basic knowledge of php so I think this question is easy for you.
if ($_POST['ccp_n'] != "") {
$ccp = filter_var($_POST['ccp_n'], FILTER_SANITIZE_NUMBER_INT);
if (!filter_var($ccp, FILTER_VALIDATE_INT)) {
$errors .= 'Insert a valid code.<br/>';
}
} else {
$errors .= 'Insert a code.<br/>';
}
I need to add a minimum and maximum number of characters (14-15) and I want to accept this characters ( - or space ) .The exact sequence is 0000-0000-0000 (the last four digits could be 5 too
Thanks
You can use preg_match and apply a regular expression.
preg_match ( string $pattern , string $TestString) See here in detail
The pattern is the problem. You need to define in detail what is allowed.
For example, the pattern:
'~^\d{4}-\d{4}-\d{4,5}$~D'
would be the whole string from start ^ to the end $. 4 digits, hyphen, 4 digits, hyphen, 4 to 5 digits.
See it here on Regexr
Update:
I added the D modifier to the end, otherwise the $ not only match to the end of the string, but also before a newline as last character in the string. See here for php modifiers in detail
Use a regular expression with preg_match(). Alternatively, you can also use sscanf() to parse the input from a string according to a format.

How to check if a string is in an array?

I basically need a function to check whether a string's characters (each character) is in an array.
My code isn't working so far, but here it is anyway,
$allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","#",".","-","_","+"," ");
$input = "Test";
$input = str_split($input);
if (in_array($input,$allowedChars)) {echo "Yep, found.";}else {echo "Sigh, not found...";}
I want it to say 'Yep, found.' if one of the letters in $input is found in $allowedChars. Simple enough, right? Well, that doesn't work, and I haven't found a function that will search a string's individual characters for a value in an array.
By the way, I want it to be just those array's values, I'm not looking for fancy html_strip_entities or whatever it is, I want to use that exact array for the allowed characters.
You really should look into regex and the preg_match function: http://php.net/manual/en/function.preg-match.php
But, this should make your specific request work:
$allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","#",".","-","_","+"," ");
$input = "Test";
$input = str_split($input);
$message = "Sigh, not found...";
foreach($input as $letter) {
if (in_array($letter, $allowedChars)) {
$message = "Yep, found.";
break;
}
}
echo $message;
Are you familiar with regular expressions at all? It's sort of the more accepted way of doing what you're trying to do, unless I'm missing something here.
Take a look at preg_match(): http://php.net/manual/en/function.preg-match.php
To address your example, here's some sample code (UPDATED TO ADDRESS ISSUES IN COMMENTS):
$subject = "Hello, this is a string";
$pattern = '/[a-zA-Z0-9 #._+-]*/'; // include all the symbols you want to match here
if (preg_match($pattern, $subject))
echo "Yep, matches";
else
echo "Doesn't match :(";
A little explanation of the regex: the '^' matches the beginning of the string, the '[a-zA-Z0-9 #._+-]' part means "any character in this set", the '*' after it means "zero or more of the last thing", and finally the '$' at the end matches the end of the string.
A somewhat different approach:
$allowedChars = array("a","b","c","d","e");
$char_buff = explode('', "Test");
$foundTheseOnes = array_intersect($char_buff, $allowedChars);
if(!empty($foundTheseOnes)) {
echo 'Yep, something was found. Let\'s find out what: <br />';
print_r($foundTheseOnes);
}
Validating the characters in a string is most appropriately done with string functions.preg_match() is the most direct/elegant method for this task.
Code: (Demo)
$input="Test Test Test Test";
if(preg_match('/^[\w +.#_-]*$/',$input)){
echo "Input string does not contain any disallowed characters";
}else{
echo "Input contains one or more disallowed characters";
}
// output: Yes, input contains only allowed characters
Pattern Explanation:
/ # start pattern
^ # start matching from start of string
[\w +.#-] # match: a-z, A-Z, 0-9, underscore, space, plus, dot, atsign, hyphen
* # zero or more occurrences
$ # match until end of string
/ # end pattern
Significant points:
The ^ and $ anchors are crucial to ensure that the entire string is validated versus just a substring of the string.
The \w (a.k.a. "any word character" -> a shorthand character class) is the easy way to write: [a-zA-Z0-9_]
The . dot character loses its "match anything (almost)" meaning and becomes literal when it is written inside of a character class. No escaping slash is necessary.
The hyphen inside of a character class can be written without an escaping slash (\-) so long as the it is positioned at the start or end of the character class. If the hyphen is not at the start/end and it is not escaped, it will create a range of characters between the characters on either side of it.Like it or not, [.-z] will not match a hyphen symbol because it does not exist "between" the dot character and the lowercase letter z on the ascii table.
The * that follows the character class is the "quantifier". The asterisk means "0 or more" of the preceding character class. In this case, this means that preg_match() will allow an empty string. If you want to deny an empty string, you can use + which means "1 or more" of the preceding character class. Finally, you can be far more specific about string length by using a number or numbers in a curly bracketed expression.
{8} would mean the string must be exactly 8 characters long.
{4,} would mean the string must be at least 4 characters long.
{,10} would mean the string length must be between 0 and 10.
{5,9} would mean the string length must be between 5 and 9 characters.
All of that advice aside, if you absolutely must use your array of characters AND you wanted to use a loop to check individual characters against your validation array (and I certainly don't recommend it), then the goal should be to reduce the number of array elements involved so as to reduce total iterations.
Your $allowedChars array has multiple elements that contain the space character, but only one is necessary. You should prepare the array using array_unique() or a similar technique.
str_split($input) will run the chance of generating an array with duplicate elements. For example, if $input="Test Test Test Test"; then the resultant array from str_split() will have 19 elements, 14 of which will require redundant validation checks.
You could probably eliminate redundancies from str_split() by calling count_chars($input,3) and feeding that to str_split() or alternatively you could call str_split() then array_unique() before performing the iterative process.
Because you're just validating a string, see preg_match() and other PCRE functions for handling this instead.
Alternatively, you can use strcspn() to do...
$check = "abcde.... '; // fill in the rest of the characters
$test = "Test";
echo ((strcspn($test, $check) === strlen($test)) ? "Sigh, not found..." : 'Yep, found.');

Categories