Remove HTML tags from String in PHP with strip_tags()

strip_tags is a PPH function which can strip HTML and PHP tags from a given string. This function allows to specify which HTML tags to keep via $allowed_tags parameter. It tries to return a string with all NULL bytes, HTML and PHP tags.

strip_tags is helpful when developer want to display content as text, without any HTML.

strip_tags ( string $string , array|string|null $allowed_tags = null ) : string
$html = '<b>Welcome to my website!</b>';
$output = strip_tags($html); //'Welcome to my website!'

The parameter is either given as string, or as of PHP 7.4.0, as array. In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used.

$html = 'Hello <b>Adam</b><br />Welcome';
$output = strip_tags($html, '<br>'); // 'Hello Adam<br />Welcome'

A more complicated HTML string

$html = '<section class="about-area pt-70">
        <div class="about-shape-2">
            <img src="images/about-shape-2.svg" alt="shape">
        </div>
        <div class="container">
            <div class="row">
                <div class="col-lg-6 order-lg-last">
                    <div class="about-content mt-50 wow fadeInLeftBig" data-wow-duration="1s" data-wow-delay="0.5s">
                        <div class="section-title">
                            <div class="line"></div>
                            <h3 class="title">Our vision and values</h3>
                        </div> <!-- section title -->                        
                    </div>
                </div>
                <div class="col-lg-6 order-lg-first">
                    <div class="about-image text-center mt-50 wow fadeInRightBig" data-wow-duration="1s" data-wow-delay="0.5s">
                        <img src="images/about2.svg" alt="about">
                    </div> <!-- about image -->
                </div>
            </div> <!-- row -->
        </div> <!-- container -->
    </section>';

$output = strip_tags($html); //'Our vision and values'

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close