How to remove all attributes from a tag using PHP

I have a project using preg_replace. I try to search on google: how to remove all attributes from a tag using PHP? The results are complicated. Then i fixed it myself.

What is HTML Attributes

HTML attributes provide additional information about HTML elements. The HTML standard does not require lowercase attribute names. The title attribute (and all other attributes) can be written with uppercase or lowercase like title or TITLE. The HTML standard does not require quotes around attribute values. Double quotes around attribute values are the most common in HTML, but single quotes can also be used. In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes:

HTML Attributes

  • All HTML elements can have attributes
  • Attributes provide additional information about elements
  • HTML Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like: name=”value”

Remove all attributes from all html tag

The first result show me a way to remove all attributes from any html tag. It cover all html tag like: a href, p, br, table… It mean all html tag will become basic tag.

Here is function:

For example if you have html code like this:

The RegExp here mean:

When using above function it will output like this:

That’s not what i expected.  What i want is something to remove only  p tag or a tag or br tag.

PHP remove all attributes from a specific tag

After sometime searching and i discover the best way to do it using PHP.
Here is the code which i used:

Apply this code for whatever tag you want to remove attributes.
For example, i have table like this:

Then i apply above code:

Here is output after i used preg_replace:

Well, very clean, right.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *