Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a slug?

Tags:

regex

php

I'm having trouble creating a Regex to match URL slugs (basically, alphanumeric "words" separated by single dashes)

this-is-an-example

I've come up with this Regex: /[a-z0-9\-]+$/ and while it restricts the string to only alphanumerical characters and dashes, it still produces some false positives like these:

-example
example-
this-----is---an--example
-

I'm quite bad with regular expressions, so any help would be appreciated.

like image 457
federico-t Avatar asked Oct 08 '13 19:10

federico-t


1 Answers

You can use this:

/^
  [a-z0-9]+   # One or more repetition of given characters
  (?:         # A non-capture group.
    -           # A hyphen
    [a-z0-9]+   # One or more repetition of given characters
  )*          # Zero or more repetition of previous group
 $/ 

This will match:

  1. A sequence of alphanumeric characters at the beginning.
  2. Then it will match a hyphen, then a sequence of alphanumeric characters, 0 or more times.
like image 106
Rohit Jain Avatar answered Oct 18 '22 16:10

Rohit Jain