使用PHP将ASCII文本转换为HTML
为用户提供一个用于输入信息的文本框是很常见的,但是通常人们希望在文本中包括换行符和链接,并且他们希望该网站按原计划进行布局。以下函数会将任何ASCII文本字符串转换为近似的HTML。
function ascii2html($s) { $s = htmlentities($s); //尝试通过双换行符分割文本 $paragraphs = split("\n\n",$s); if(count($paragraphs) < 2) { //如果没有足够的数组,则尝试将其拆分为单个 $paragraphs = split("\n",$s); }; for($i = 0,$j = count($paragraphs);$i < $j;$i++) { //在URL周围创建链接 $paragraphs[$i] = preg_replace('/((ht|f)tp:\/\/[^\s&]+)/','$1',$paragraphs[$i]); //在电子邮件地址周围创建链接 $paragraphs[$i] = preg_replace('/[^@\s][email protected]([-a-z0-9]+\.)+[a-z]{2,}/i','$0',$paragraphs[$i]); //制作段落 $paragraphs[$i] = ''.$paragraphs[$i].'
'; }; //加入所有段落并返回 return join("\n",$paragraphs); }
要对此进行测试,请使用以下文本示例。
$text = "this is some text that splits across several lines and has some links like this one here http://www.hashbangcode.com which will be used to create a bunch of html";
并这样调用ascii2html()函数。
echoascii2html($text);
这将产生以下输出。
this is some text
that splits across several
lines and
has some links like this
one here http://www.hashbangcode.com which
will be used to create a bunch of html
strip_tags()在使用此功能之前,请谨慎使用该功能清除ASCII文本,因为这可能会导致无效的HTML。