Reputation: 117
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";
}
Upvotes: 0
Views: 99
Reputation: 47864
Most accurately, check the start of the string with ^
, then require one or more alphanumeric characters, then optionally allow one of your nominated delimiting characters followed by one or more aphanumeric characters then match the position of the end of the string. Demo
/^[a-z\d]+([._ -][a-z\d]+)*$/i
This will give a match for strings such as: A
, 8
, R2d2
, sn_a_k_e
, and barley bar
Non-matches include: _
, Foo_
, .foolery
For comparison's sake, @ghoti's answer will not match a (valid) single alphanumeric character. Same with @hsz's answer. @Mirko's answer is advising unnecessary escaping. @bkwint's answer isn't fully refined and fails in a few scenarios.
Upvotes: 0
Reputation: 46826
What about this?
/^([a-zA-Z0-9]+[._ -]?)+[a-zA-Z0-9]$/
The start and end with alnum are obvious here, but the internal part basically enforces that any of [._-]
will be surrounded by "NOT [._-]
"
Is that what you want?
Upvotes: 1
Reputation: 152206
Try with:
/^([[:alnum:]]+[._ -]?)+[[:alnum:]]+$/
alnum
is an alias for letters and digits.
Upvotes: 1
Reputation: 2447
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
Upvotes: 0