2015-06-28 41 views
0

這裏是我的代碼刪除所有的屬性:PHP從標籤

$content2= preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

此代碼將刪除所有標籤的所有屬性在我的網站,但我要的是僅從form標籤刪除屬性。這是我曾嘗試:

$content2 = preg_replace("/<form([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 

,並從一個相關的問題

$content2 = preg_replace("/<(form[a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $content1); 
+0

什麼是$ content1和它應該是什麼? – Droid

+0

$ content1只是我整個網站的源代碼 –

回答

1

這應該爲你做。

<?php 
$content1 = '<form method="post">test</form><form>2</form><form action=\'test\' method="post" type="blah"><img><b>bold</b></form>'; 
$content2 = preg_replace("~<form\s+.*?>~i",'<form>', $content1); 
echo $content2; 

輸出:

<form>test</form><form>2</form><form><img><b>bold</b></form> 

說明和演示:https://regex101.com/r/oA1fV8/1

\s+是需要空格開幕form標籤後,如果我們有,我們假定有一個屬性後,所以我們使用.*?這需要一切,直到下一個>。我們不需要捕獲組,因爲您想要的只是一個空的form元素,對吧?

+0

我的示例只有3個'preg_replace'參數。你正在運行的代碼是什麼? – chris85

+0

wooooooooow它真的很有用,非常感謝你! –

+0

我會點擊答案 –

0

答:

<?php 
function stripArgumentFromTags($htmlString) { 
    $regEx = '/([^<]*<\s*[a-z](?:[0-9]|[a-z]{0,9}))(?:(?:\s*[a-z\-]{2,14}\s*=\s*(?:"[^"]*"|\'[^\']*\'))*)(\s*\/?>[^<]*)/i'; // match any start tag 

    $chunks = preg_split($regEx, $htmlString, -1, PREG_SPLIT_DELIM_CAPTURE); 
    $chunkCount = count($chunks); 

    $strippedString = ''; 
    for ($n = 1; $n < $chunkCount; $n++) { 
     $strippedString .= $chunks[$n]; 
    } 

    return $strippedString; 
} 
?> 

然後使用調用稱呼它

$strippedTag = stripArgumentFromTags($initialTag); 

Related question with more answers

+0

它不適合我如何從

標籤中刪除屬性? –