Cliff Odebala Clarke
Cliff Odebala Clarke

Reputation: 198

Problems With My Php Text to Link Conversion Function

I am writing a BBCode conversion function which converts plain text to hyperlink but I noticed that contents which contains well formatted links are also converted wrongly instead of being ignore. The output of the code block below gives two hyperlinks with one correct and the other wrong. How do I avoid reconverting already hyperlinked text.

<?php
function make_links_clickable($text){
     $prepared_str = str_replace('www.','http://www.',$text);
     $strip_double_str = str_replace('http://http://','http://',$prepared_str); 
     return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $strip_double_str); }

$strbody = "He was also the Head of Department, Environmental Health 
            in  the School of Health Technology, Orji River, 
            Enugu, and member of several professional bodies. <br/>

            Source: <br/>
            <a href='http://vanguardngr.com/2015/09'>This is Already hyperlinked</a> <br>
            http://vanguardngr.com/2015/09/buhari-appoints-abonyi-as-registrar-of-ehorecon/";

echo make_links_clickable($strbody);
?>

Upvotes: 1

Views: 63

Answers (2)

Rohan Khude
Rohan Khude

Reputation: 4883

string contains links that have to be transformed into html link tags. Here is a simple PHP function.

function autolink($string)
{
$content_array = explode(" ", $string);
$output = '';

foreach($content_array as $content)
{
//starts with http://
if(substr($content, 0, 7) == "http://")
$content = '<a href="' . $content . '">' . $content . '</a>';

//starts with www.
if(substr($content, 0, 4) == "www.")
$content = '<a href="http://' . $content . '">' . $content . '</a>';

$output .= " " . $content;
}

$output = trim($output);
return $output;
}

Call the above function and print it

echo autolink($string);

Upvotes: 1

Rohan Khude
Rohan Khude

Reputation: 4883

Add this line before echo

$strbody=strip_tags($strbody);

strip_tags removes html tags from string. As our text having <a> tag so strip_tags removes it.

Upvotes: 0

Related Questions