geoffs3310 geoffs3310 - 2 months ago 7x
PHP Question

preg_match to validate a URL slug

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

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!


I hope this code is self-explanatory:


function test_username($username){
    if(preg_match('/^[a-z][-a-z0-9]*$/', $username)){
        echo "$username matches!\n";
    } else {
        echo "$username does not match!\n";


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 ($).