Preg_match for checking URL pool

I allow the user to create their own profile on my site so that they can choose what their URL will be. So, for example, if their name is John Smith, they may want to log in to john-smith, and then their profile URL will be www.mysite.com/john-smith.

I need to use preg_match to verify that what they enter is a valid url. So, here are the rules that he must follow in order to be valid:

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

Can someone help me, please, I'm good at PHP, but trash with regex!

+6
source share
3 answers

I hope this code is self explanatory:

<?php function test_username($username){ if(preg_match('/^[az][-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 test_username () function checks its argument against the template:

  • begins ( ^ ) ...
  • with one letter ( [az] ) ...
  • followed by any number of letters, numbers or hyphens ( [-a-z0-9]* ) ...
  • and after that it has nothing ( $ ).
+14
source

The best decision:

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

Tests:

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

Enjoy it!

+4
source

Pretty simple, assuming the first character should be a letter ...

 /[az]{1}[a-z0-9\-]*/i 
+1
source

Source: https://habr.com/ru/post/905864/


All Articles