0

How do you check if a given URL matches at least a sitename?

I have:

$url_to_match = 'http://sub.somesite.com/';

I want to say "MATCH found" for input starting with http://sub.somesite.com only.

Any help would be very much appreciated.

3 Answers 3

2

Use PHP's parse_url():

$url = 'http://sub.somesite.com/';
if ('sub.somesite.com' === parse_url($url, PHP_URL_HOST)) {
    // we have a match
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the right tool for the job. Depends if the OP wants to validate the scheme too.
Thanks a lot, did the job well. I was confused with lots of regex approaches :) But this is simpler.
1

use parse_url

example:

function match_url($base,$input)
{
    $base_host = parse_url($base,PHP_URL_HOST);
    $input_host = parse_url($input,PHP_URL_HOST);
    if( $base_host === $input_host ) {
        return true;
    }
    else
    {
        return false;
    }   
}
$base_url = 'http://sub.somesite.com';
$input_url = 'http://sub.somesite.com//bla/bla';
echo (match_url($base_url,$input_url)) ? "URL matched" : "URL mismatched";

Comments

0

I think you need to tell us what you are doing since this request makes no design sense.

However, to answer the question.

if(strpos($url_to_match, 'http://sub.anothersite.com/bla') !== FALSE) print 'bad string';

3 Comments

This is wrong usage of strpos() (syntax error), but yes, based on the question, you need to use strpos(), read here lt.php.net/strpos
@AurelijusValeiša, good catch, I can't believe I forgot the $haystack. XD
I have clarified my question. I am afraid doing checking the opposite is not what I meant. Thanks

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.