0

I have been looking around for a regex expression that will spit out just the 'stackoverflow' part and no www. or .com etc. All I could find was to check if the url's were valid... I have used php's url filter to determine that much I now am looking to determine which site it is.

I have never written an expression before so I am hoping someone can check it/recommend a better solution.

preg_match('@^(?:http://)(?:www.)?([^.]+)@i', $url, $matches)

edit: All the url's I am dealing with are .com if that helps

4 Answers 4

5

Have you considered PHP's parse_url() function?

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

1 Comment

the function is really great.... except it still leaves me with sometimes being 'www.' and sometimes no 'www.' so I will still have to preg_replace the www.
2

one-liner without using regular expressions!!!

$url = 'http://stackoverflow.com';
$d = array_shift( explode( '.', str_replace('www.', '', parse_url( $url, PHP_URL_HOST )) ) );
echo $d;

2 Comments

haha... its only a one liner because you stuck it all in one line :) Regardless it works well. Its the best so far.
This fails. Use this string www.myusualhost-test.co.in.php53-1.dfw1-2.websitetestlink.com and it gives me myusualhost-test whereas I just want myusualhost-test.co.in.php53-1.dfw1-2.websitetestlink.
0

If you know that the thing you're having is a URL and the domain end in .com a simple thing like

preg_match('#([^\.]*)\.com#', $url, $matches);

should do the trick.

While this will fail on a domain like www.com.foo.com but might be enough, depending on your situation.

Comments

0
preg_match('#https?://(?:www.)?(.*?)\.com#i', $str, $match);

Comments

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.