Need help with stripping url and etc..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tech0925
Forum Commoner
Posts: 47
Joined: Wed Nov 09, 2011 2:46 pm

Need help with stripping url and etc..

Post 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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Need help with stripping url and etc..

Post 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'];
}
tech0925
Forum Commoner
Posts: 47
Joined: Wed Nov 09, 2011 2:46 pm

Re: Need help with stripping url and etc..

Post by tech0925 »

ok great, thanks!
tech0925
Forum Commoner
Posts: 47
Joined: Wed Nov 09, 2011 2:46 pm

Re: Need help with stripping url and etc..

Post 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
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Need help with stripping url and etc..

Post 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.
Post Reply