Liam
Liam

Reputation: 47

preg_match - to allow only one dash

I'm using preg_match and its working to allow; numbers, letters and dash. but i want to limit the dash to 1 only. i tried added {1} before and after the dash but its still allowing more than one. what am i doing wrong?

if (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
                $nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
            } else {

This is the code that i'm using.

Thanks

Upvotes: 2

Views: 2605

Answers (3)

Arshad Syed
Arshad Syed

Reputation: 403

 $username = "abc-edf-tru-ksk-5-ll-hr-foam-6-inch-queen-anroid-phone-stackoverflow-72-x-70-x-6290321_1";

This below code allow hypens(-) and underscore(_)

if(preg_match('/^[a-zA-Z0-9\-\_]+(-[a-zA-Z0-9\-\_]+)*$/', $username))
{
            echo "The username you selected valid characters are hypens,underscores, letters and numbers.";
}

allow only hypen(-)

if(preg_match('/^[a-zA-Z0-9\-]+(-[a-zA-Z0-9\-]+)*$/'), $username))
{
            echo "The username you selected valid characters are hypens(only), letters and numbers.";
}

allow only underscore(_)

if(preg_match('/^[a-zA-Z0-9\_]+(-[a-zA-Z0-9\_]+)*$/'), $username))
{
            echo "The username you selected valid characters are underscores(only),underscores, letters and numbers.";
}

not allow hypens, underscores and symbols

if(preg_match('/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/'), $username))
{
            echo "The username you selected valid characters are letters and numbers.";
}

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

Since you seem to validate a string that can contain one or zero hyphens in an alphanumeric string, you may use a negative lookahead in your pattern to fail the match if 2 hyphens are found:

"/^(?![^-]*-[^-]*-)[A-Za-z0-9-]+$/D"
   ^^^^^^^^^^^^^^^^

Pattern details:

  • ^ - start of a string
  • (?![^-]*-[^-]*-) - fail the match if there are 2 hyphens separated with 0+ chars other than -
  • [A-Za-z0-9-]+ - 1 or more alphanumeric chars or hyphens
  • $ - the very end of the string (since /D modifier is used).

See a regex demo (pattern modified to account for a multiline string input).

Note that if you want to disallow - to appear at the start/end of the string, and several consecutive -s, use a more straight-forward pattern:

"/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)?$/D"

where ^[A-Za-z0-9]+ will match 1+ alphanumeric chars at the start of the stirng, and (?:-[A-Za-z0-9]+)?$ will match 1 or 0 occurrences of a - followed with 1+ alphanumeric chars at the end of the string.

Upvotes: 1

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

Make an extra test for the dash count to keep it simple.

if (!preg_match("/^[A-Za-z0-9\-]+$/", $username) || substr_count($username,'-') > 1) {
  $nameErr = "The username you selected was invalid.<br>Valid characters are dashes (one only), letters and numbers.";
}

Upvotes: 1

Related Questions