Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Regex: Test for custom URLs

I have a site where users can create their own profile pages with their own Custom URLs. For example: http://www.website.com/MyProfilePage or http://www.website.com/JohnnysPage

I need a regular expression that only allows a-Z 0-9 and - (hyphens). No spaces or other characters.

So, for example it would...

FAIL ON THESE STRINGS

http://www.website.com/MyProfilePage 
My Profile Page 
My.Profile.Page 
My_Profile_Page 
My/Profile/Page 
Katie'sPage

etc. etc.

PASS ON THESE STRINGS

MyProfilePage
KatiesPage
MyProfilePage
Davids-Page
TheBestPage-2001

etc. etc.

Thanks!

Upvotes: 0

Views: 118

Answers (3)

Alp
Alp

Reputation: 29739

preg_match() to the rescue:

$pattern = '/^[a-zA-Z0-9\-]+$/';
$match = preg_match($pattern, "My.Profile.Page"); // returns false
$match = preg_match($pattern, "MyProfilePage"); // returns true

Working demo

Upvotes: 2

lafor
lafor

Reputation: 12776

preg_match('/^[a-zA-Z0-9\-]+$/',$string)

Upvotes: 2

Toto
Toto

Reputation: 91385

I would say simply:

^[a-zA-Z0-9-]+$

Upvotes: 1

Related Questions