Skip to content

Instantly share code, notes, and snippets.

@admariner
Forked from jonlabelle/strip_tag_attribs.md
Created January 11, 2026 20:56
Show Gist options
  • Select an option

  • Save admariner/8612f4ae2a57689bdde97d189fb5e0f5 to your computer and use it in GitHub Desktop.

Select an option

Save admariner/8612f4ae2a57689bdde97d189fb5e0f5 to your computer and use it in GitHub Desktop.
This Regular Expression removes all attributes and values from an HTML tag, preserving the tag itself and textual content (if found).

Strip HTML Attributes

<([a-z][a-z0-9]*)[^>]*?(/?)>
token explanation
< match < at beginning of tags
( start capture group $1 - tag name
[a-z] match a through z
[a-z0-9]* match a through z or 0 through 9 zero or more times
) end capture group
[^>]*? match anything other than >, zero or more times, not-greedy (wont eat the /)
(/?) capture group $2 - / if it is there
> match >

Add some quoting, and use the replacement text <$1$2> it should strip any text after the tagname until the end of tag /> or just >.

Example

Before

HTML containing style attributes.

<p style="padding:0px;">
	<strong style="padding:0;margin:0;">hello</strong>
</p>

After

HTML attributes removed.

<p>
	<strong>hello</strong>
</p>

PHP Example

$with_attr    = '<p style="padding:0px;"><strong style="padding:0;margin:0;">hello</strong></p>';
$without_attr = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(/?)>/i",'<$1$2>', $with_attr);

echo $without_attr
<p><strong>hello</strong></p>

stackoverflow post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment