我有这个输出:<a href="#">sdfsdfsd</a>gdsfgsdfgsdgsdggsdfg
问题是此函数将所有 html 标签转换为纯文本,除了那些带有 url 的标签,如 www.facebook.com (将其转换为 <a href="www.facebook.com">www.facebook.com</a>
):
function validate_text($text = '') {
// This method is used internally as a FILTER_CALLBACK
if (mb_strlen($text, 'utf8') < 1)
return false;
// Encode all html special characters (<, >, ", & .. etc) and convert
//$str = nl2br(htmlspecialchars($text));
$str = htmlspecialchars($text);
// the new line characters to <br> tags:
// Remove the new line characters that are left
$str = str_replace(array(chr(10), chr(13)), '', $str);
$text = preg_replace('#(script|about|applet|activex|chrome):#is', "''1:", $str);
$ret = ' ' . $text;
$ret = preg_replace("#(^|['n ])(['w]+?://['w'#$%&~/.'-;:=,?@'[']+]*)#is", "''1<a href='"''2'" target='"_blank'">''2</a>", $ret);
$ret = preg_replace("#(^|['n ])((www|ftp)'.['w'#$%&~/.'-;:=,?@'[']+]*)#is", "''1<a href='"http://''2'" target='"_blank'">''2</a>", $ret);
$ret = preg_replace("#(^|['n ])([a-z0-9&'-_.]+?)@(['w'-]+'.(['w'-'.]+'.)*['w]+)#i", "''1<a href='"mailto:''2@''3'">''2@''3</a>", $ret);
//$ret = preg_replace("#^*@([)([0-9-])(])#is", "''1<a href='"http://''2'" target='"_blank'">''2</a>", $ret);
$ret = substr($ret, 1);
return $ret;
}
我想要从<a href="#">something</a> <small>hello</small>
到<a href="#">something</a>sadfsafasf <small> hello </small>
strip_tags()
将从字符串中删除所有 html 标签,但您指定为允许的标签除外。
编辑:根据您在下面的评论;
要将包含 HTML 标记的字符串显示为文本,而不让浏览器解析需要使用 htmlspecialchars()
或 htmlentities()
的标记。然后,要将@mention替换为链接,请使用正则表达式并preg_replace()
。
这是您追求的(我认为)的示例:-
<?php
$string = "Some text with some <span>HTML tags in it</span> and a @mention to someone";
// Turn special characters into html entities
$new_string = htmlspecialchars($string);
// Replace @mention with a link
$output = preg_replace("/@('w+)/",'<a href="http://www.example.com/profiles/$1">$1</a>',$new_string);
// Will produce 'Some text with some <span>HTML tags in it</span> and a <a href="http://www.example.com/profiles/mention">mention</a> to someone'
echo $output;
?>