2011-11-24 46 views
0

我有這個問題:如何檢查每個HTML標籤是否關閉?

用戶可以添加一個HTML描述,它會顯示在他的個人資料;當我顯示用戶列表時,我也希望顯示這個描述。
因爲它可能太長,我會限制它到一個固定的長度,但這樣做,我可以打破HTML語法留下一些標籤打開。

我該如何檢查everthing是否正常,如果需要,關閉任何打開的標籤?

回答

2

@ tampe125這不是我的代碼,但它看起來像是有效的。

<?php /** * close all open xhtml tags at the end of the string 

* * @param string $html 

* @return string 

* @author Milian <[email protected]> 

*/function closetags($html) { 

    #put all opened tags into an array 

    preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result); 

    $openedtags = $result[1]; #put all closed tags into an array 

    preg_match_all('#</([a-z]+)>#iU', $html, $result); 

    $closedtags = $result[1]; 

    $len_opened = count($openedtags); 

    # all tags are closed 

    if (count($closedtags) == $len_opened) { 

    return $html; 

    } 

    $openedtags = array_reverse($openedtags); 

    # close tags 

    for ($i=0; $i < $len_opened; $i++) { 

    if (!in_array($openedtags[$i], $closedtags)){ 

     $html .= '</'.$openedtags[$i].'>'; 

    } else { 

     unset($closedtags[array_search($openedtags[$i], $closedtags)]); } 

    } return $html;} ?> 
+0

謝謝,我會嘗試儘快 – tampe125

+0

不客氣,它似乎會工作,雖然我還沒有嘗試過。我從http://www.kirupa.com/forum/showthread.php?343478獲取答案 - Close-all-open-HTML-tag – Boundless

+0

這是否解決了問題? – Boundless

1

這是一個簡單的javascript驗證程序,它執行基本標記檢查。 XML validator

唯一的問題是,它會停在第一個錯誤,所以你需要解決一次一個問題。