带有锚点<a>标签、http:// 或URL的PHP注释以及其余的HTML标签是纯文本


php comment with a an anchor <a> tag, http:// or url and the rest of the html tags are plain text

我有这个输出:<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 &lt;small&gt; hello &lt;/small&gt;

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 &lt;span&gt;HTML tags in it&lt;/span&gt; and a <a href="http://www.example.com/profiles/mention">mention</a> to someone'
echo $output;
?>