-2

I'd like to get some help regarding PHP. Let's say I have a string ($fullname). I want to validate that it's in the form of "Firstname_Lastname". For example, make sure that it's "Nathan_Phillips" and not "Nathan Phillips" or "Nathan122" etc. Can you guys help me with the function?

Thanks in advance! :-)

------------ EDIT ------------- Thank you guys! Managed to do that. Also added the numbers filter. Here's the function:

function isValidName($name)
{
    if (strcspn($name, '0123456789') != strlen($name))
        return FALSE;
    $name = str_replace(" ", "", $name);
    $result = explode("_", $name);
    if(count($result) == 2)
        return TRUE;
    else
        return FALSE;
}

Usage example:

if(isValidName("Test_Test") == TRUE)
    echo "Valid name.";
else
    echo "Invalid name.";

Thanks again!

Ariel Weinberger
  • 2,195
  • 4
  • 23
  • 49
  • Please share your attempts so far as @GordonM said. Some thoughts are to check for spaces, split on the underscore, etc. Show us what you're trying. – davidethell Oct 30 '12 at 18:54
  • I tried to split the input strings to two string by using the "split" function, splitted by the "_" (underscrore) character, though it didn't prevent users from putting several cells like "Nathan_Joshua_Phillips", or "Nathan_12345". – Ariel Weinberger Oct 30 '12 at 18:58

1 Answers1

2

Maybe try something like this:

function checkInput($input) {
    $pattern = '/^[A-Za-z]{2,50}_[A-Za-z]{2,50}/';
    return preg_match($pattern, substr($input,3), $matches, PREG_OFFSET_CAPTURE);
}

This will accept a string containing 2-50 alphabetic characters, followed by an underscore, followed by 2-50 alphabetic characters.

I'm not the best with regex, so I invite corrections if anyone sees a flaw.

If you have special characters (è, í, etc.), the regex I gave probably won't accept it. Also, it won't accept names like O'Reilly or hyphenated names. See this:

Regex for names

I'll let you track down all the exceptions to the regex for names, but I definitely think regex is the way to go.

Community
  • 1
  • 1
woz
  • 10,888
  • 3
  • 34
  • 64