我正在编写一个BBCode转换函数,它将纯文本转换为超链接,但我注意到包含格式良好的链接的内容也被错误地转换而不是被忽略。下面代码块的输出给出了两个超链接,其中一个是正确的,另一个是错误的。如何避免重新转换已经超链接的文本。
<?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);
?>
string包含必须转换为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);
在echo
前添加一行$strbody=strip_tags($strbody);
strip_tags从字符串中删除HTML标签。因为我们的文本有<a>
标签所以strip_tags删除它