How to validate a domain name using Regex & Php?

前端 未结 6 669
失恋的感觉
失恋的感觉 2020-12-03 05:27

I want a solution to validate only domain names not full urls, The following example is what i\'m looking for:

domain.com -> true
domain.net -> true
do         


        
6条回答
  •  不思量自难忘°
    2020-12-03 05:44

    Please try this expression:

    ^(http[s]?\:\/\/)?((\w+)\.)?(([\w-]+)?)(\.[\w-]+){1,2}$
    

    What it actually does

    • optional http/s://
    • optional www
    • any valid alphanumeric name (including - and _)
    • 1 or 2 occurrences of any valid alphanumeric name (including - and _)

    Validation Examples

    • http://www.test.com
    • test.com.mt

提交回复
热议问题