views:

406

answers:

4

hi

i want something like this

  1. the user enter a website link

  2. i need check the link if the link doesn't start with 'http://' I want to append 'http://' to the link .

how can I do that in PHP ?

+7  A: 
if (0 !== stripos($url, 'http://')) {
   $url = 'http://' . $url;
}
Tom Haigh
Your answer is correct, but I can't stand it when people put the two operands of the comparison operators in that order.
Lucas Oman
@Lucas: Surely that's just a matter of personal taste. What is your reasoning?
Tom Haigh
I'm with Lucas on this. My reasoning is that it doesn't make sense if you read it as an english sentence. "if zero does not equal the outcome of this function..."
_Lasar
It's evidently less readable. But there is a rationale for it in C-derived languages where you can accidentally write ‘if (a=0)’. ‘if (0=a)’ will get caught quickly. Though personally I don't use this style, it is a matter of taste and coding standards.
bobince
It is personal taste. I always use this notation and I find it more readable.
andy.gurin
In mathematics, you always put the variable on the left and the quantity on the right. As a habit formed from that, I always follow Lucas's order.
Karan
+3  A: 

I'll recommend a slight improvement over tom's

if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) {
   $url = 'http://' . $url;
}

However, this will mess up links that use other protocols (ftp:// svn:// gopher:// etc)

Tom Ritter
yes, i thought of that after I saw your answer...
Tom Haigh
+1  A: 
if (!preg_match("/^http:\/{2}/",$url)){
    $url = 'http://' . $url;
}
Chris Kloberdanz
+1  A: 

I would check for the some letters followed by a colon. According to the URI specifications a colon is used to separate the "schema" (http, ftp etc.) from the "schema specific part". This way if somebody enters (for example) mailto links these are handled correctly.

reefnet_alex