0

So here is what I need to do.

If an user enters this: http://site.com I need to remove http:// so the string will be site.com , if an user enters http://www.site.com I need to remove http://www. or if the user enters www.site.com I need to remove www. or he can also enter site.com it will be good as well.

I have a function here, but doesn't work how I want to, and I suck at regex.

preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['link'])
1
  • just want to notice, that sometimes "domain.tld" is not the same as "www.domain.tld" Commented Sep 29, 2010 at 23:40

5 Answers 5

3

Use filter_var() instead.

if (filter_var($_POST['link'], FILTER_VALIDATE_URL)) {
    // valid URL
} else {
   // not valid
}
Sign up to request clarification or add additional context in comments.

Comments

3

There is also parse_url function.

Comments

2

I don't think I'd use regex for this, since you're only really checking for what is at the beginning of the string. So:

$link = $_POST['link'];
if (stripos($link, 'http://') === 0)
{
    $link = substr($link, 7);
}
elseif (stripos($link, 'https://') === 0)
{
    $link = substr($link, 8);
}
if (stripos($link, 'www.') === 0)
{
    $link = substr($link, 4);
}

should take care of it.

Comments

0

i always go with str_replace haha

str_replace('http://','',str_replace('www.','',$url))

6 Comments

If there happens to be another 'www.' in the string except at the beginning, this approach would have a problem.
Removing of "www." can be a problem in any case ;-)
alrighty, how bout this str_replace('','',str_replace('http://','',$url))
@Ascherer You would never reach the outer str_replace with anything that it would replace if the original $url is valid. You would already have stripped off the http://.
yeah, i did it backwards, im gonna stop commenting on this one cause im getting tired, but u get the picture, just a simple way, that with work, could also be used.
|
0

I think what you're looking for is a multi-stage preg_replace():

$tmp = strtolower($_POST['link']) ;
$tmp = preg_replace('/^http(s)?/', '', $tmp);
$domain = preg_replace('/^www./', '', $tmp) ;

This simplifies the required regex quite a bit too.

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.