Codeformer
Codeformer

Reputation: 2300

Regular Expression to check if the URL is under a particular domain

I need a regular expression that finds if the given URL is under my website.

For example :

http://www.my_domain.com/internal_page should give true.
www.my_domain.com/internal_page should give false.
http://www.my_domain.com should give false. ( should have a "/" after .com  ).
http://www.my_domain.com:dfdf should give false.

-- Thank you

Upvotes: 0

Views: 166

Answers (4)

Robert
Robert

Reputation: 20286

Use this

http:\/\/www\.my_domain\.com\/.*

you should really to show some efforts before posting.

  • http:\/\/ - means http://

  • www\.my_domain\.com is equal to www.mydomain.com

  • \/.* means / and 0 or any characters in the end of expression.

Upvotes: 1

Vinoth Babu
Vinoth Babu

Reputation: 6852

Below is the pattern you want,

  $pattern = "#^https?://www.my_domain\.com(/.*)?$#";

  $test    = 'http://www.google.com';

  if ( preg_match( $pattern, $test ) )
  {
      echo $test, " <strong>matched!</strong><br>";
  } else {
      echo $test, " <strong>did not match.</strong><br>";
  }

Upvotes: 1

Orangepill
Orangepill

Reputation: 24655

You could just do this

 $url = "http://www.my_domain.com/internal_page";
 $host = "www.my_domain.com";
 if(strpos($url, "http://".$host."/") === 0){
      // we have a winner
 } else {
      // no good
 }

Upvotes: 0

johnd
johnd

Reputation: 526

How about this?

http:\/\/www\.my_domain\.com\/(.+)

It passes the four tests you gave

Upvotes: 0

Related Questions