- Instant help with your Php coding problems

Remove all attributes from HTML tags in PHP

Question:
How to remove all attributes from HTML tags in PHP?
Answer:
$text = '<div class="test"><p onmousemove="javascript:alert(1);">Clean <a href="#">text</a></p></div>';

$cleanText = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/si",'<$1$2>', $text);
Description:

There are cases where you do not need to remove HTML tags from a text, but only the attributes that belong to the tag. In this case, a regular expression can quickly bypass the problem.

With preg_replace you can remove all attributes from the given string.

Note: In some cases, such as if the HTML is syntactically incorrect, this solution will not give the correct result.   

Share "How to remove all attributes from HTML tags in PHP?"
Tags:
remove all attributes with regex, regex remove element attributes
Technical term:
Remove all attributes from HTML tags in PHP
Interesting things
ChatGPT in a nutshell