facebook icon twitter icon angle down linkedin icon youtube icon
Home > Blog > remove-html-tags-except-few-in-php

How to remove all HTML tags except particular tags in PHP

In some cases you need to remove HTML tags from string for security reason or any other needs. You can do it simply by using strip_tags() function. It is a built-in function of PHP.

If you want to keep some particular tags, that also possible using this function.

In this article, I included this simple method with brief explanation.

Basic syntax:

strip_tags(‘content’,'tags you want to allow');

You need to provide two parameters.

1. Content is the first parameter where you need to place your content which may includes HTML tags.

2. In second parameter, you need to include one or more tags which you do not want to remove.

In the placement of parameters, you can use PHP variables.

Discussion: remove all HTML tags from a string except few ones

In the following method, you can preserve your desired HTML tags while removing all tags.

Example:

<?php
//input string
$content= '<p style="color:red;"><b>I want to remove this tag.</b></p> <i>But I do not want to remove this one.</i> <u>And also not this one.</u>';
//removing all html tags except few
$string = strip_tags($content,'<I><u>');
//showing result
echo htmlentities($string);
?>

Output:

I want to remove this tag. <i>But I do not want to remove this one.</i> <u>And also not this one.</u>

Just use the starting tag which you do not want to remove.

No matter whether the tags contain any attribute or not, all will be removed through strip_tags() function.

Note: it is not necessarily using htmlentities() function. I used it to show a more clear result. It is also a PHP built-in function.

If you want to remove all tags, then simply skip the second parameter.

Example:

<?php
//input string
$content= '<p style="color:red;"><b>I want to remove this tag.</b></p> <i>But I do not want to remove this one.</i> <u>And also not this one.</u>';
//removing all html tags except few
$string = strip_tags($content);
//showing result
echo htmlentities($string);
?>

Output:

I want to remove this tag. But I do not want to remove this one. And also not this one.

Tarikul islam

About Torikul islam

Torikul islam is a professional web developer and affiliate marketer. Join Torikul to learn how to start a website and operate it well. He started his Web Developement career from Bangladesh Association of Software and Information (BASIS) in 2015. Later he continiued his journey to expanding knowledge and sharing it with others.

Write a Comment

No comment yet