1

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.

3
  • 1
    inb4 THE PONY HE COMES. Commented Oct 17, 2013 at 10:43
  • @Ben Fortune - what was that? Commented Oct 17, 2013 at 11:04
  • stackoverflow.com/a/1732454/2615209 Commented Oct 17, 2013 at 11:14

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

this is removing all the tags, except <a> tag. I need to keep all the tags with removed atributes. e.g.: <span style="float:left;"> to just <span>. The regex I have given above works fine, but if tag is <a href="blah blah url"> becomes <a> so I need a solution to prevent this <a href="blah blah url"> tag and it's attributes as is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.