Hrishi
Hrishi

Reputation: 13

php regex to remove attributes of html tags except hyper links <a> tags

Please suggest me PHP regex for preg_replace to remove just all the attributes from HTML tags except <a> tag.

I tried already:preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>',$htmltext);

It works fine for all the HTML tags but for <a> tag it removes href, title and target attributes.

Please suggest me the required changes in above regex or please share the working one.

Thanks in advance.

Upvotes: 1

Views: 2983

Answers (1)

anubhava
anubhava

Reputation: 785146

to remove all the tags from HTML tags except <a> tag.

No need of regex, you can just use strip_tags function:

$html = strip_tags($html, '<a>');

UPDATE: preg_replace to remove just all the attributes from HTML tags except from <a>. You can use this negative lookahead based regex:

$htmltext = preg_replace("~<(?!a\s)([a-z][a-z0-9]*)[^>]*?(/?)>~i",'<$1$2>', $htmltext);

Upvotes: 4

Related Questions