Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove attributes from an html tag?

How can I use php to strip all/any attributes from a tag, say a paragraph tag?

<p class="one" otherrandomattribute="two"> to <p>

like image 222
stunnaman Avatar asked Apr 20 '09 21:04

stunnaman


People also ask

How do you remove an item in HTML?

Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

How do I delete a class attribute?

The removeClass() method is used to remove one, multiple, or all the class names from the class attributes of the matched elements. In an HTML document, elements may have a class attribute with one or more class names for that element.

What is delete attribute used for?

The Delete Attribute refactoring allows you to delete a set of attribute definitions on a set of XML tag. If this refactoring is invoked, all attributes matching the selected attribute name on tags with the selected tag name may be removed.

How do you change attributes in HTML?

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.


1 Answers

Although there are better ways, you could actually strip arguments from html tags with a regular expression:

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

The above could probably be written in less characters, but it does the job (quick and dirty).

like image 148
Jacco Avatar answered Oct 01 '22 16:10

Jacco