Page 1 of 1

Need help with stripping url and etc..

Posted: Sat Feb 11, 2012 4:58 pm
by tech0925
I have a website which if someone adds a link and does not use the http:// it will cause a 404 error when clicked on.

Lets say the variable is

$url = 'www.mysite.com';

or

$url = 'mysite.com';

or when its actually right

$url = 'http://www.mysite.com';


How can I strip the url and then add back the http://www. to the url so I can be assured they are all right? I am a little lost with this.

Re: Need help with stripping url and etc..

Posted: Sat Feb 11, 2012 8:20 pm
by Celauran
You don't want to 'add back' the www. as it may not have been there in the first place. As for the protocol, you could try something like this:

Code: Select all

if (!preg_match('/^http:\/\//', $_POST['url']))
{
    $_POST['url'] = 'http://' . $_POST['url'];
}

Re: Need help with stripping url and etc..

Posted: Sat Feb 11, 2012 8:22 pm
by tech0925
ok great, thanks!

Re: Need help with stripping url and etc..

Posted: Sat Feb 11, 2012 8:34 pm
by tech0925
Works great! Thanks!

Let me ask you this. What about if someone puts a link in an text box designed for more than just a link? For example:

Code: Select all

$bio = 'This is my bio. I may or may not include a link but in this case I did. <a href="www.mysite.com">My Site</a>';
How do I go about checking for the a tag and making sure the http is there? :D

Re: Need help with stripping url and etc..

Posted: Sat Feb 11, 2012 8:59 pm
by Celauran
Same basic idea. Check for href=" if it exists, check for href="http://. If that doesn't, do a string replace. Where you'll run into trouble is when they include two links; one with the leading http:// and one without. The important part, that I forgot to add last night, is that it's probably best to avoid doing this at all. Give your users instructions and let them follow them. In my experience, trying to anticipate and correct for every possible user error serves only to introduce new, unforeseen errors.