Reputation: 13
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);
Upvotes: 0
Views: 630
Reputation: 23892
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?
Upvotes: 1
Reputation: 1098
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
Upvotes: 0