7

I am letting the user create their own profile on my site so they can choose what their url will be. So for example if their name is John Smith they might like to enter john-smith and then their profile URL would be www.mysite.com/john-smith.

I need to use preg_match to validate that what they enter is a valid URL slug. So here are the rules that it must fulfill to be valid:

it must contain at least one letter and it can only contain letters, numbers and hyphens

Can someone help me out please I am good at PHP but rubbish with regex!

3 Answers 3

16

I hope this code is self-explanatory:

<?php function test_username($username){ if(preg_match('/^[a-z][-a-z0-9]*$/', $username)){ echo "$username matches!\n"; } else { echo "$username does not match!\n"; } } test_username("user-n4me"); test_username("user+inv@lid") 

But if not, the function test_username() test its argument against the pattern:

  • begins (^) ...
  • with one letter ([a-z]) ...
  • followed by any number of letters, numbers or hyphens ([-a-z0-9]*) ...
  • and doesn't have anything after that ($).
Sign up to request clarification or add additional context in comments.

3 Comments

This fails for invalid--slug
@Victor, you can try: /^[a-z](-[a-z0-9]+)*$/
@ArthurRonconi this works better : /^[a-z]+(-[a-z0-9]+)*$/
7

Better solution:

function is_slug($str) { return preg_match('/^[a-z0-9]+(-?[a-z0-9]+)*$/i', $str); } 

Tests:

  • fail: -user-name
  • fail: user--name
  • fail: username-
  • valid: user-name
  • valid: user123-name-321
  • valid: username
  • valid: USER123-name
  • valid: user-name-2

Enjoy!

6 Comments

something wrong, not match with user-name, only u-name regex101.com/r/0hYjoV/1
@ArthurShlain thanks. It's fixed, try again please.
Now better, but check this variant: user-name-2
@ArthurShlain fixed again =)
How to allow underscore also with this ? Same rule need to apply as with dash, cannot occur in start/end, but can in the middle.
|
1

Pretty simply, if we assume that the first character must be a letter...

/[a-z]{1}[a-z0-9\-]*/i 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.