0

I have an input box where user can enter their domain. I want to make sure the domain should be like that:

example.com
hello.com
okay.com

NOT

www.example.com
https://www.hello.com
https://okay.com

I mean no http, https and www at the beginning of the domain.

So far I got this:

} elseif( !preg_match('/^[a-zA-Z. ]+$/', $domain) ) {
    $output['message'][] = 'Your domain should be start with http, https or www but can contain (.)com';
} 

How can I improve this preg_match function to get the desire validation?

23
  • 1
    and www at the beginning of the domain -- please clarify why subdomains are not permitted? Commented Jun 9, 2022 at 8:02
  • 1
    "Your domain should be contain only characters." - that is quite a misleading error message, when your pattern actually allows not only for dots, but for spaces for some reason as well. And do you really want to reject any user input here, if their domain name would contain digits or hyphens ...? Commented Jun 9, 2022 at 8:03
  • 1
    @shingo That regex fails for s3.amazonaws.com Commented Jun 9, 2022 at 8:07
  • 1
    Does this answer your question? PHP validation/regex for URL - if you just want the domain without a protocol, why not strip it from user input before using it Commented Jun 9, 2022 at 8:08
  • 2
    "I think you don't understand what I Need" - and I am not too sure you understand what you need :-) "I just don't want the http, https or www from the begging of the string" - that alone would not be a reason to reject domain names that contain digits or hyphens then. Commented Jun 9, 2022 at 8:31

1 Answer 1

2

Try this /^(?!(www|http|https)\.)\w+(\.\w+)+$/

It matches

example.com
hello.com
okay.com
example.123
1.example.com.cn
s3.amazonaws.com

It doesn't match

www.example.com
https://www.hello.com
https://okay.com
http.example.com

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your reply but what about httpyahoo.com or httpsyahoo.com or wwwyahoo.com ?
They match, if you don't want to match these domains, just remove the first dot.
I did it but not working. I enter this text httpyahoo.com but showing me my validation error. Its should be passed.
I am using this ! preg_match('/^(?!(www|http|https))\w+(.\w+)+$/', $domain)
Sorry, I missed backslashes before dot.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.