Summary: in this tutorial, you’ll learn how to use the PHP strip_tags()
function to strip HTML and PHP tags from a string.
Introduction to the PHP strip_tags() function
The strip_tags()
function returns a new string with all HTML and PHP tags removed from the input string.
Here’s the syntax of the strip_tags()
function:
strip_tags ( string $string , array|string|null $allowed_tags = null ) : string
Code language: PHP (php)
The strip_tags()
function has the following parameters:
$string
is the input string.$allowed_tags
is one or more tags that you want to retain in the result string. The$allowed_tags
can be a string that contains the list of tags to retain e.g.,'<div>p>’. If you use PHP 7.4.0 or later, you can pass an array of tags instead of a string, e.g.,['div','p']
.
PHP strip_tags() function examples
Let’s take some examples of using the strip_tags()
function.
1) Using PHP strip_tags() function to remove all HTML tags
The following example shows how to use the strip_tags()
function to strip all HTML tags from the contents of the page https://www.php.net:
<?php
$html = file_get_contents('https://www.php.net/');
$plain_text = strip_tags($html);
echo $plain_text;
Code language: PHP (php)
How it works.
- First, use the
file_get_contents()
function to download the HTML contents from the php.net. - Second, strip all the HTML tags from the HTML contents using the
strip_tags()
function.
2) Using PHP strip_tags() function with some allowed tags
The following example uses the strip_tags()
function to strip all HTML tags from the contents of the page https://www.php.net but keeps the following tags: ['h1', 'h2', 'h3', 'p', 'ul', 'li', 'a']
:
<?php
$html = file_get_contents('https://www.php.net/');
$simple_html = strip_tags($html, ['h1', 'h2', 'h3', 'p', 'ul', 'li', 'a']);
echo $simple_html;
Code language: PHP (php)
Summary
- Use the PHP
strip_tags()
function to strip HTML and PHP tags from a string.