Hi,
I want to be able to allow administrators for a CMS to enter a URL and have it appear as a link. But, of course, I don't want to allow any old html.
I wrote a short function that can do this, but I have 2 concerns:
- Is there a better way than what I've done (see code below)? It seems pretty dang clunky.
- How can I detect text line breaks?
The reason for 2. is that my function looks for the first space after a substring beginning with "http://" to determine where the URL ends. However, if someone entered text with a line break right after the URL, my script thinks the next word is part of the URL
function text_tags($text)
{
# THIS FUNCTION TAKES TEXT, PREPARES IT FOR WEB PRESENTATION USING htmlspecialchars AND MAKING
# ANYTHING BEGINNING WITH 'http://' A LINK
$new_text = $text;
$text_length = strlen($text);
$end_text = $text;
$a = strpos($end_text, "http://");
#LOOP AS MANY TIMES AS THERE ARE URLs IN THE TEXT:
for ($i = 1; $i <= substr_count($text, "http://"); $i++)
{
#FIND THE POSITION OF THE NEXT LINK AND CUT EVERYTHING BEFORE THAT FROM $end_text:
$pos = strpos($end_text, "http://");
$end_text = substr($end_text, $pos);
#FIND THE END OF THE URL BY LOOKING FOR A SPACE
# -- IF THERE IS NONE, THE LINK GOES TO THE END OF THE STRING:
$sp_pos = strpos($end_text, " ");
if ($sp_pos < 1)
$sp_pos = strlen($end_text);
#ISOLATE THE URL:
$link = substr($end_text, 0, $sp_pos);
#REMOVE THE LINK FROM $end_text (WHERE WHITTLING AWAY AT IT):
$end_text = substr($end_text, $sp_pos +1);
#CREATE A REPLACEMENT STRING FOR THE LINK, WHICH WILL GET BY HTMLSPECIALCHARS:
$new_link = str_replace("http://", "{A HREF}", $link);
$new_link = $new_link."{A MID}".$link."{A OFF}";
#NOW USE THAT TO REPLACE THE LINK IN A COPY OF THE STRING:
$new_text = str_replace($link, $new_link, $new_text);
}
$new_text = htmlspecialchars($new_text);
#REPLACE THE DUMMY LINK PARTS WITH REAL html:
$new_text = str_replace("{A HREF}", "<a href='http://", $new_text);
$new_text = str_replace("{A MID}", "'>", $new_text);
$new_text = str_replace("{A OFF}", "</a>", $new_text);
return ($new_text);
}