Php: Fastest Way to Check for Invalid Characters (All But A-Z, A-Z, 0-9, #, -, ., $)

PHP: fastest way to check for invalid characters (all but a-z, A-Z, 0-9, #, -, ., $)?

Try this function:

function isValid($str) {
return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
}

[^A-Za-z0-9.#\-$] describes any character that is invalid. If preg_match finds a match (an invalid character), it will return 1 and 0 otherwise. Furthermore !1 is false and !0 is true. Thus isValid returns false if an invalid character is found and true otherwise.

PHP: check for invalid characters (all but a-z, A-Z, 0-9, _, -, ., @)?

preg_match('/[a-z0-9._-\@]/i', $email)

This will return true if any valid characters are found but you want to match any non-valid characters - so invert the character class:

preg_match('/[^a-z0-9\._\-\@]/i', $email)

Alternatively you could require that it only contains the valid characters:

if (!(preg_match('/^([a-z0-9\._\-\@]+)$/', $email)) {

BTW as an email address (more specifically an ADDR_SPEC validator) this sucks big time - it will pass non-valid email addresses and fail valid ones.

Who told you that '%' is invalid in a mailbox name?

Currently I use this:

/^[a-z0-9\._%+!$&*=^|~#%'`?{}/\-]+@([a-z0-9\-]+\.){1,}([a-z]{2,20})$/gi

(which still excludes some valid ADDR_SPECs - but for specific reasons - and has some issues with idn)

...but would suggest you just use filter_var() and ditch the regex.

Yii2 replace symbol from name

Use regular expression search and replace:

//Perform a regular expression match first
if(preg_match('/[.$%-]+/', $file_name) == 1)
{
//perform regular expression search and replace
$new_name = preg_replace('/[.$%-]+/', '_', $file_name);

}

PHP Empty and data validation

You have a typo in the preg_match, you type $$field (2x$) instead of $field, your regex is fine it will match:

 - a character between a - z (case insensitive)
or
- a digit between 0 - 9
or
- a "space" character.

Update code to answer @Andrius Naruševičius comment

$validate = array("Category" => $productCategory, "Name" => $productName);
$error = '';
foreach ($validate as $key => $field)
{
if (preg_match('/^[a-z\d ]{4,20}$/i',$field))
{
$error.= $field;
}
}

if($error)
{
echo $error;
exit;
}

PHP Replace string allow only a-z A-Z 0-9 _ and . (dot)

if (preg_match('/^[\w\.]+$/', $username)) {
echo 'Username is valid';
}

\w - matches [a-zA-Z0-9_]+

Need to Add regex (php) for at least 1 special char

Try this

$special   = preg_match('/[^a-zA-Z\d]/', $motopass);

Regex for password must contain exactly one uppercase character

Try this one:

^(?=[^A-Z]*[A-Z][^A-Z]*$)(?=.*[#@-])[A-Za-z#@-]{8,}$

Demo: https://regex101.com/r/Fr6znT/1

Breakdown:

  • (?=[^A-Z]*[A-Z][^A-Z]*$) at the position it is means: "The whole expression should be 'any number of non uppercase chars', followed by 'one uppercase char', followed by 'any number of non uppercase chars'".


Related Topics



Leave a reply



Submit