Preg Split ignore case - php

I'm trying to ignore uppercase or lowercase with the code below to detect whether the user is blocked or not. Is working when matching the username or email but with the case problem, the validation does not work. How to make it case insensitive? Thanks for helping.
$msg = "something";
$blocked = preg_split('/[\r\n]([a-z])([A-Z])+/', admin_get_option('blocked_users'), -1, PREG_SPLIT_NO_EMPTY);
if ( isset($form['username_or_email']) && in_array( $form['username_or_email'], $blocked) ) {
$errors['username_or_email'] = $msg;
}
if ( isset($form['user_login']) && in_array( $form['user_login'], $blocked) ) {
$errors['user_login'] = $msg;
}
if ( isset($form['user_email']) && in_array( $form['user_email'], $blocked) ) {
$errors['user_email'] = $msg;
}

" i " Modifier Makes the match case insensitive

Related

Gravity Forms regex for US ZIP code

I'm trying to set up some form validation for a Gravity Form that I've created. One of the fields that I need to validate is a US ZIP code. I want to pass ZIPs that follow the nnnnn and nnnnn-nnnn patterns. Here's my code:
if ( $field->type == 'address' ) {
$zip = rgar( $value, $field->id . '.5' );
if ( preg_match( "(^(?!0{5})(\d{5})(?!-?0{4})(|-\d{4})?$)", $zip ) && ! $field->get_input_property( '5', 'isHidden' )
) {
$result['is_valid'] = false;
$result['message'] = empty( $field->errorMessage ) ? __( 'Please enter a valid ZIP code (ie. 00000 or 00000-0000).', 'gravityforms' ) : $field->errorMessage;
} else {
$result['is_valid'] = true;
$result['message'] = '';
}
}
My form continues to fail validation and I can't figure out why. I've double checked that .5 is the correct input field number of the ZIP code. Any suggestions?
My form can be found at http://marcusjones.wpengine.com/
shouldn't be easier to use:
/(^\d{5}$)|(^\d{5}-\d{4}$)/
or other function fe:
function isValidPostalCode(postalCode, countryCode) {
switch (countryCode) {
case "US":
postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
break;
default:
postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;
}
return postalCodeRegex.test(postalCode);
}
and "if" you'll add quite simple.

How to display an array $key with this pattern promote-1 for which 1 can be any whole number?

function name( $key, $value ) {
switch( $key ) {
case 'name':
break;
// this is where I would determine the key with this pattern 1-100
case 'promote-'.count++ :
break;
}
}
When I echo the $key sample outputs would be contact_number, card_name and the pattern I would like to determine promote-1, promote-2 and so on. The second option "case 'promote-'.count++" is the pattern I need to determine. That any 'promote-1' to 'promote-100' will fall on that option
Use of switch case is very restricted. Here is a working solution for you.
function name( $key, $value ) {
if(strpos($key,'-') > 0){
$key_arry = explode('-' , $key);
if($key_arry[0] == 'promote' && ($key_arry[1] > 0 || $key_arry[1] <= 100)){
echo 'Patern is promote-1, promote-2......promote-100';
}else{
echo 'anything else';
}
}
}
name('promote-2' , 1);
try with regex
case (preg_match('/promote-\d/', $key) ? true : false) :
// do stuff for people whose name is John, Johnny, ...
break;
'/promote-\d/'this will check for patterns - promote-<any digit>

how to know if it's email or username inputed

Hello everyone i want to ask question my html form, requires to input username/Email that you can put.
Then it searches by username or email if in database that account exists if yes process.
The script works, but only with email.
My problem is how to identify in input field is the user written an username or email? Now it checks both but for some reason it dosen't detect username only email typed.
function getUserEmailExist( $input )
{
global $database;
if( preg_match( '/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i', $input ) ) {
$type = 2;
$get = $database->checkExistRecovery( $input, $type );
}
if( preg_match( '/[^0-9A-Za-z]/', $input ) ) {
$type = 1;
$get = $database->checkExistRecovery( $input, $type );
}
if( $get ) {
$this->updateRecover( $input, $type );
} else {
return false;
}
}
You need to move your email if statement below.
Because if the input is an email, it's going to match the second preg match anyway.
So you're overwriting your $type variable.
Fixed.
function getUserEmailExist( $input )
{
global $database;
if( preg_match( '/[A-Za-z0-9]+/', $input ) ) {
$type = 1;
$get = $database->checkExistRecovery( $input, $type );
}
if( preg_match( '/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i', $input ) ) {
$type = 2;
$get = $database->checkExistRecovery( $input, $type );
}
if( $get ) {
$this->updateRecover( $input, $type );
} else {
return false;
}
}
I think you want your second regex to be /[A-Za-z0-9]+/. You are currently looking for anything that doesn't contain those characters.
Why do you care about all that validation logic? I can't see your actual DB queries, but it seems you could easily do something like this:
SELECT * FROM users
WHERE email = ? OR username = ?
Where ? would be the email or username value.

PHP case insensitive usermame match

ANSWER EDIT:
The fix was to change:
if (get_user_data( $input_user, $logindata ) === $input_pwd ) {
to
if (get_user_data(strtolower($input_user), $logindata) === $input_pwd ) {
so that the username is forced to lowercase. I just have to be conscious to store my usernames as all lowercase too.
I am aware of strcasecmp. I am not sure how that would apply to my working code though, as you can only compare 2 variables.
Am I able to make preg_match case insensitive in the context of my working code below?
Can I add the /i regex to my preg_match command to a returned variable?
I just want the username that is entered by the user (including domain name) to be case insenstive. (ie. uSeRnAMe#dOmAIN1.CoM) without having to add every combination of valid username to my pseudo database!
This is my working code:
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}
You can do a case insensitive match in PHP with i. For instance, the following will print 'This matches!':
<?php
if ( preg_match('/def/i', 'ABCDEF') ) {
echo 'This matches!';
}
?>
So just add i to the pattern, and the case will be ignored.
One approach if you want case-insensitive usernames is to always lowercase a new one when you store it, and then to always lowercase the comparing value when you check. (This is a lot faster than using preg_match.)

PHP email address validation question

I was wondering how can I just check if an # sign has been included when an email address is entered into the input box? I'm using PHP.
Here is my php code.
if (isset($_POST['email']) && strlen($_POST['email']) <= 255)
Could just use a simple:
filter_var($email, FILTER_VALIDATE_EMAIL)
If you absolutely must use a Regex, than I would recommend (This is to signify that regex should NOT be used to validate email addresses):
"/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?
[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?
[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-
\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-
\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-
\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-
\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-
9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-
9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-
9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-
9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-
9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-
9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-
9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD"
if(strstr($email,"#"))
{
// true
}
A better way to find if the email is fine is by using this regex
\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b
in preg_match()
You might want to have this checked using a preg instead of a loose strpos($_POST['email'],"#"):
if (preg_match($_POST["email"],"/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i")) {
// do stuff
}
Source
Just a quote from the docs on strstr. "If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead."
Another thing on strpos I've noticed is that it's unsafe to just check for truth of strpos because if $needle is at 0'th position in $haystack, a simple check will fail. You must check it's type as well (at least I do). This will print "notfound found".
<?php
$str = 'foobar';
if (strpos($str, 'foo')) {
echo 'found ';
} else {
echo 'notfound ';
}
// proper...
if (strpos($str, 'foo') !== false) {
echo 'found ';
} else {
echo 'notfound ';
}
This regex implements rfc2822:
[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*#(?:a-z0-9?.)+a-z0-9?
However, in practice, I find this more apposite for the purpose of capturing an email address (or more specifically an ADDR-SPEC) via a web page:
^[a-z0-9._%+!$&*=^|~#%\'`?{}/-]+#[a-z0-9.-]+.[a-z]{2,6}$
You are welcome to use my free PHP function is_email() to validate addresses. It's available to download here. It doesn't use a regex because I can't find one that fully implements RFC 5321.
is_email() will ensure that an address is fully RFC 5321 compliant. It can optionally also check whether the domain actually exists and has an MX record.
You shouldn't rely on a validator to tell you whether a user's email address actually exists: some ISPs give out non-compliant addresses to their users, particularly in countries which don't use the Latin alphabet. More in my essay about email validation here: http://isemail.info/about.
This is how you do an email validation check with PHP:
function check_email($email) {
// Remove trailing and leading spaces.
$email = trim($email);
// Must have an # sign.
$at = strpos($email, '#');
if( $at === false )
return 1; //false;
list($mailbox, $hostname) = explode('#', $email);
// Check that there is a mailbox and a hostname
if( $mailbox == '' || $hostname == '' )
return 2; //false;
// Only one # allowed
if( strpos($hostname, '#') !== false )
return 3; //false;
// Must be a . in the hostname
if( strpos($hostname, '.') === false )
return 4; //false;
// Can't have a double in either mailbox or hostname
if( strpos($hostname, '..') !== false || strpos($mailbox, '..') !== false )
return 5; //false;
// Mailbox can't start or end with a .
if( substr($mailbox, 0, 1) == '.' || substr($mailbox, strlen($mailbox)-1, 1) == '.' )
return 6; //false;
// Hostname can't start or end with a .
if( substr($hostname, 0, 1) == '.' || substr($hostname, strlen($hostname)-1, 1) == '.' )
return 7; //false;
// Check that all characters are valid
if( str_replace(' ' , '', strtr(strtolower($mailbox), 'abcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+-/=?^_`{|}~.', ' ')) != '' )
return 8; // false;
if( str_replace(' ' , '', strtr(strtolower($hostname), 'abcdefghijklmnopqrstuvwxyz0123456789_-.', ' ')) != '' )
return 9; //false;
return 0; //true;
}
This is what I use. Works perfectly.
public function valid_mail($mail)
{
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $mail))
{
return false;
} else {
return true;
}
}

Categories