How to Use strip_tags() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `strip_tags()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP, the `strip_tags()` function is used to strip HTML and PHP tags from a string. This can be useful when you want to display user-generated content on a webpage while ensuring that any HTML or PHP code within it is not executed.

Here’s how you can use the `strip_tags()` function in PHP 8.1 and 8.2 with examples:

Basic Usage:

<?php
$text = "<p>This is <b>bold</b> and <i>italic</i> text.</p>";
$stripped_text = strip_tags($text);
echo $stripped_text;
?>

Output:

This is bold and italic text.

Specifying Allowed Tags:

You can also specify which HTML tags you want to allow by providing them as the second argument to the `strip_tags()` function:

<?php
$text = "<p>This is <b>bold</b> and <i>italic</i> text.</p>";
$allowed_tags = "<b><i>";
$stripped_text = strip_tags($text, $allowed_tags);
echo $stripped_text;
?>

Output:

This is <b>bold</b> and <i>italic</i> text.

Using Arrays to Specify Allowed Tags:

Starting from PHP 8.1, you can use arrays to specify allowed tags:

<?php
$text = "<p>This is <b>bold</b> and <i>italic</i> text.</p>";
$allowed_tags = ['b', 'i'];
$stripped_text = strip_tags($text, $allowed_tags);
echo $stripped_text;
?>

Output:

This is <b>bold</b> and <i>italic</i> text.

Using strip_tags() with a Callback (PHP 8.2):

In PHP 8.2, you can use a callback function to process each tag and its attributes individually. Here’s an example:

<?php
$text = "<p>This is <b>bold</b> and <i>italic</i> text.</p>";
$stripped_text = strip_tags($text, function ($tag) {
return $tag === 'b' ? '<strong>' : '';
});
echo $stripped_text;
?>

Output:

<p>This is <strong>bold</strong> and italic text.</p>

These examples demonstrate the usage of the `strip_tags()` function in PHP 8.1 and 8.2, including basic usage, specifying allowed tags, using arrays for allowed tags, and utilizing a callback function in PHP 8.2.