2012-03-20 30 views
2

我有這樣的HTML代碼:PHP正則表達式去除MSO標籤

$html = "<P style="mso-margin-top-alt: auto; mso-margin-bottom-alt: auto; padding: 4px;" class=MsoNormal>text</P>"; 

我需要刪除所有mso- *標記,結果將是:

$html = "<P style="padding: 4px;" class=MsoNormal>text</P>"; 

我怎麼做PHP的? 非常感謝

+0

的可能重複[PHP來清理粘貼微軟輸入(HTTP://計算器.com/questions/379342/php-to-clean-up-pasted-microsoft-input) – 2012-03-20 11:37:36

+0

@Pekka不是一個好的重複imo。它基本上只是說使用HTMLPurifier或Tidy,並且只有一個答案。 – Gordon 2012-03-20 11:42:00

+1

@戈登我猜這取決於OP真正想要什麼。如果他想清理所有微軟的東西,HTMLPurifier確實是我所知道的最好的方法。如果他想要*完全*他在上面顯示的內容(而沒有其他內容),則不同。 – 2012-03-20 11:43:55

回答

-1

代碼:

$html = "<p style='mso-margin-top-alt: auto; mso-margin-bottom-alt: auto; padding: 4px;' class=MsoNormal>text</P>"; 

$cleanHtml = preg_replace('(mso-[a-z\-: ]+;)i', '', $html); 

echo $cleanHtml; 

輸出:

<P style='padding: 4px;' class=MsoNormal>text</P> 
3

這會工作:

echo preg_replace(
    '(
     mso- # match anything with the mso vendor prefix 
     .+? # followed by at least one character 
     ;  # up to the first semicolon 
     [ ]* # and an optional space 
    )xi', 
    '',  // replace that match with nothing 
    $html 
); 

但是,如果有更多的只是HTML中的一行$html,看看Grabbing the href attribute of an a element學習如何容易和可靠地獲取從屬性html中的元素。然後使用上面的正則表達式來替換節點值。

+0

http://codepad.org/AaajCxvk - 我很高興我得到了與專家一樣的答案! – jon 2012-03-20 11:46:46

0

你也可以試試這個;

(mso-[^:]*:[^;]*;) 

但是,不要忘了不與正則表達式解析HTML,這是一個非常大的罪!

0
preg_replace('/mso-.+?:\s*?.+?;/s', '', $html); 
0
<?php 
$string = '<P style="mso-margin-top-alt: auto; mso-margin-bottom-alt: auto; padding: 4px;" class=MsoNormal>text</P>'; 
$patterns = '/mso-(.*?);/'; 
$replacements = ''; 
echo preg_replace($patterns, $replacements, $string); 
?> 
0

我測試過Dr.Kameleon的解決方案:它工作正常,但它不不適用於所有情況。例如,對於下面的代碼,mso- *屬性不會刪除:

<p style='mso-margin-top-alt:auto;mso-margin-bottom-alt:auto' class=MsoNormal>text</P> 

(我刪除一些空格和「」)。

所以,我建議你Dr.Kameleon的代碼的一些改進:

$cleanHtml = preg_replace('(mso-[a-z0-9\s\-:;]+)i', '', $html); 

最佳方面