2015-09-16 20 views
1

我正在写一个BBCode转换函数,它将纯文本转换为超链接,但我注意到包含格式良好的链接的内容也被错误地转换而不是被忽略。下面的代码块的输出给出了两个超链接,一个正确,另一个错误。如何避免重新转换已经超链接的文本。我的PHP文本链接转换函数的问题

<?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а-яА-Я()[email protected]:%_+.~#?&;//=]+)!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); 
?> 

回答

1

字符串包含必须转换为html链接标记的链接。这是一个简单的PHP函数。

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; 
} 

调用上面的函数并打印

echo autolink($string); 
+0

现在就测试你的脚本,但它仍然没有让它超链接已经形成。它扭曲了它使得格式不正确。 str中有两个链接,一个已经格式化为超链接,另一个链接文本应该转换为超链接。 您的函数对纯文本起作用,但对于已经超链接的文本不起作用。 –

+0

我用代码更新了答案......我测试了输出......现在按照它。 如果它给出正确的输出。那么请接受答案 –

+0

哪个答案? 我试过两种方法,但它仍然扭曲已经超链接的文本。尝试使用$ strbody的值运行你的函数。 您会注意到链接断开。只有第二个链接有效。 –

0

呼应

$strbody=strip_tags($strbody); 

用strip_tags从字符串中删除HTML标记之前添加此行。由于我们的文字有<a>标签,所以strip_tags将其删除。

+0

感谢罗汉Khude的努力帮助,但我想要的是两个环节的工作。我希望第一个链接未被转换器触及,因为它已经格式良好,而第二个链接是纯文本链接,应该转换为超链接。 尝试了你的建议后,我注意到所有的链接都被删除了,这不是我想要的结果。我想要链接。 –