Remove HTML tags from a String in PHP

This article, will discuss multiple ways to remove html tags from a string in PHP.

Table Of Contents

Background

When working with PHP, especially in web development, you often encounter strings that contain HTML tags. There are cases where you need to strip these tags for text processing, data sanitization, or displaying plain text. For example, you might have a string like this:

$originalString = "<p>This is a <em>sample</em> string</p>";

The goal is to remove all the HTML tags and get the following output:

"This is a sample string"

Let’s explore some methods to accomplish this.

Solution 1: Using strip_tags()

The strip_tags() function in PHP is specifically designed to strip HTML and PHP tags from a string. It’s the simplest and most direct way to remove HTML tags.

Let’s see the complete example,

<?php
$originalString = "<p>This is a <em>sample</em> string</p>";

// Remove all HTML tags
$noHtmlString = strip_tags($originalString);

echo $noHtmlString;
?>

Output

This is a sample string

In this code:
– strip_tags($originalString) removes all HTML and PHP tags from $originalString.
– The resulting string is free of any HTML tags, providing plain text.

Solution 2: Using strip_tags() with Allowed Tags

Sometimes, you might want to keep certain HTML tags for formatting purposes while removing others. The strip_tags() function allows you to specify which HTML tags should not be removed.

Let’s see the complete example,

<?php
$originalString = "<p>This is a <em>sample</em> <a href='#'>string</a></p>";

// Remove all HTML tags except <em> and <a>
$noHtmlString = strip_tags($originalString, '<em><a>');

echo $noHtmlString;
?>

Output

This is a <em>sample</em> <a href='#'>string</a>

In this code:
– We use strip_tags($originalString, ‘<em><a>’) to remove all HTML tags except <em> and <a>.
– This way, you can preserve certain HTML tags for formatting while removing others.

Summary

Removing HTML tags from a string in PHP is efficiently handled by the strip_tags() function. It offers the flexibility to either remove all tags or keep specific ones, making it a versatile tool for various text processing scenarios in web development.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top