Search code examples
phpregexstringvalidationdelimited

Validate string to be alphanumeric optionally separated by solitary whitelisted delimiters in the middle of the string


This is what I want to achieve:

Part 1: string must start with alphanumeric characters then it may or may not have a dot, underscore, hyphen, or space`.

Part 2: it must finish with alphanumeric characters.

The part 1 can repeat forever, but it must finish with part 2.

It tried like a million ways of doing it and it never works. With the code that I have below if I put "Test__test" (with TWO "_") it works when it shouldn't.

if (preg_match('/([a-zA-Z0-9]{1,}[._-]{0,1})+[a-zA-Z0-9]{1,}$/',$pseudo))
{
    echo "Ok";
} else {
    echo "Error";
}

Solution

  • First you must escape the - and . like so [\._\-] because it is a special symbol, and then try adding the ^ sign in front of the regular expression