php从标记中删除所有属性

php从标记中删除所有属性

问题描述:

Here is my code:

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

This code removes all attributes from all tags in my website, but what I want is to only remove attributes from the form tag. This is what I have tried:

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

and

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

这是我的代码: p>

  $ content2 = preg_replace(  “/&lt;([az] [a-z0-9] *)[^&gt;] *?(\ /?)&gt; / i”,'&lt; $ 1 $ 2&gt;',$ content1); 
   code>  pre> 
 
 

此代码删除了我网站中所有标记的所有属性,但我想要的只是从 form code>标记中删除属性。 这就是我的尝试: p>

  $ content2 = preg_replace(“/&lt; form([az] [a-z0-9] *)[^&gt;] *  ?(\ /?)&gt; / i“,'&lt; $ 1 $ 2&gt;',$ content1);  
  code>  pre> 
 
 

和 p>

  $ content2 = preg_replace(“/&lt;(form [az] [a-z0  -9] *)[^&gt;] *?(\ /?)&gt; / i“,'&lt; $ 1 $ 2&gt;',$ content1);  
  code>  pre> 
  div>

This should do it for you.

<?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;

Output:

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

Explanation and demo: https://regex101.com/r/oA1fV8/1

The \s+ is requiring whitespace after the opening form tag if we have that we presume there is an attribute after so we use .*? which takes everything until the next >. We don't need capture groups because the only thing you want is an empty form element, right?

Answer from a related question:

<?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;
}
?>

Then use call call it like this

$strippedTag = stripArgumentFromTags($initialTag);

Related question with more answers