I want to make an if(){} statement that says if string $link starts with 'http://' then echo("<a href='" . $link . "'>Blah blah</a>"); otherwise, echo("<a href='http://www.unm.edu/~cjadams/forms/info/" . $link . "'>Blah blah</a>"); I just noticed not all of our info pages are stand alone pages that I can copy to their own directory, some actually branch out. I know this can be done with regular expressions, or maybe without, but how can I test the first seven characters of a string for "http://" ? I know there must be an easy way, right?
eregi() is your ultimate friend, gimme 10 mins and i'll post some code (if i can work it out). I'd go for the easier explode() method... Code: $urlparts = explode(':',$string); if($urlparts[0] == 'http') { echo [world link] }else { echo [local link] }
My end result: PHP: if (!$row['InfoLink']){ echo("<td width='16'><img src='http://www.unm.edu/~cjadams/images/spacer.gif' width='16'></td>"); } else { $info = $row['InfoLink']; if (substr($info, 0, 7)=="http://"){ echo("<td width='16'><a href='" . $row['InfoLink'] . "' target='_Blank'><img src='http://www.unm.edu/~cjadams/images/icon_info.gif' border='0'></a></td>\n "); } else { echo("<td width='16'><a href='http://www.unm.edu/~cjadams/forms/info/" . $row['InfoLink'] . "' target='_Blank'><img src='http://www.unm.edu/~cjadams/images/icon_info.gif' border='0'></a></td>\n "); } } It works, so I'm happy Is there a shorter way than 0,7? just curious.
or using strstr ... Code: if(strstr($string, 'http://')) { echo '<a href="'.$_POST[url].'">blah...</a>'; } else { echo '<a href="http://richthetitch.net/'.$_POST[url].'">blah..</a>'; } but much less reliable as it wont check that the first part is http://, it only knows if the string contains http://.
In this instance it would be fine, because an http:// anywhere in a url other than at the first will mess it up anyway. But I'm sticking with my first way for now. I had to paste the code in like 20 places. I just found out I should be using a while or for loop instead of pasting the same code 6 times, with the only difference being a little bit of text and a number! Thanks though, I'll go with your first reccomendation when I clean my code!
you can cut those down a little more, using shorthand if statements Code: rah == 1 ? true : false; you can nest them as well Code: rah == 1 ? true : rah == 2 ? true : false; iirc...
its the same as the syntax is any language ive used, seen it in c/perl/php/javascript seems pretty common. Yer granted i missed the $ off the variables, been reading about c recently
if(!preg_match("/^http:\/\//i", $link)) $link = "http://".$link. i think that's it. i may have escaped the forward slashes wrong. in the php tags on this forum it shows \/ as /. why does that happen? see below PHP: \/