Jump to content

Regex Expression not working :(


Genesis730

Recommended Posts

So I'm trying to get this regex to work properly, I'm wanting to only accept uppercase letters, lowercase letters, one - (hyphen) and one ' (apostrophe). Everything seems to work except when i put a ' in the input, it fails.

 

$regex = "/[^-'a-z]/i";
if (preg_match($regex,$lastname) || substr_count($lastname, "'") > 1 || substr_count($lastname, "-") > 1) {
     $errormessage = 'Last Name Invalid';
     $error += 1;                                  
}

 

Any help would be appreciated

Link to comment
https://forums.phpfreaks.com/topic/244981-regex-expression-not-working/
Share on other sites

It's workin' fine for me.

 

<?php

$lastname = "MichA-'el"; // Works
// $lastname = "MichA-'el'"; // Errors out with the second apostrophe

$regex = '/[^-\'a-z]/i';

if (preg_match($regex, $lastname) || substr_count($lastname, '\'') > 1 || substr_count($lastname, '-') > 1)
{
$errormessage = 'Last Name Invalid';
$error += 1;
}

?>

I have copied and pasted it exactly, and MichA-'el  fails on mine :( being that I'm using " in the regex i didn't even think that i had to escape a ' but even doing so I get the same result, so could there possibly be a setting that's altering something and causing my issue??

Without editing your code, it works fine for me.

 

<?php

$lastname = "miCHa-'el";

$regex = "/[^-'a-z]/i";
if (preg_match($regex,$lastname) || substr_count($lastname, "'") > 1 || substr_count($lastname, "-") > 1) {
$errormessage = 'Last Name Invalid';
$error += 1;                                  
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.