2012-04-06 137 views
-1

我有這樣的輸出:<a href="#">sdfsdfsd</a>gdsfgsdfgsdgsdggsdfgPHP註釋://或URL和html標籤的其餘部分是純文本

問題是,這個函數的所有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\#$%&~/.\-;:=,[email protected]\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret); 
    $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,[email protected]\[\]+]*)#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:\\[email protected]\\3\">\\[email protected]\\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;

+1

沒有推出自己的HTML驗證,你這樣做是錯誤的。 – zzzzBov 2012-04-06 14:05:04

+0

對不起,我不擅長RegEx我剛剛找到代碼....我該怎麼做配偶? – 2012-04-06 14:07:09

+1

[對於初學者,請勿使用RegEx來解析HTML](http://stackoverflow.com/a/1732454/497418)。 – zzzzBov 2012-04-06 14:08:44

回答

1

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; 

?> 
+0

謝謝mate!我試過了,但我的期望並不像它看起來那樣,我想要一些像twitter這樣的東西,將發佈在文本或字符串中使用錨標籤。 – 2012-04-06 14:15:29

+0

所以你想將@mention變成一個鏈接,但刪除所有其他的HTML?讓我知道你正在努力達到什麼目標,我可能會指出你在正確的方向 – rgvcorley 2012-04-06 14:21:57

+0

在這裏你去找夥伴http://stackoverflow.com/questions/10042877/jquery-mention-making-the- -output-a-link#comment12848031_10042877 有些部分已經回答。謝謝! – 2012-04-06 14:29:36