Skip to content

All topics  /  PHP

PHP - How to Remove HTML Tags From a String?

PHP ·

Teams applying “PHP - How to Remove HTML Tags From a String?” in a production project can use learn more here to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.

Hi Guys,

This example is focused on how to remove html tags from a string in php. Here you will learn how to remove all html tags from a string in php. if you have question about remove html tags from string php then i will give simple example with solution you can see remove html tags from string php. So, let's follow few step to create example of remove html tags from string php.

I will explain how to remove HTML tags form a string in php. We will show the example of clear HTML tags form a string in php. I will remove HTML tag using strip_tags() method in php.It can remove HTML tag using 2 ways from predefined method and userdefined method.i will show easy example of remove HTML tags form a string in php.

Here following example of remove HTML tags form a string in php

Example: 1 Predefined Method


In this example ,you can removes HTML tags using strip_tags() method.

<?php
//declaring a string with html tags
$html_string="Welcome <span>to</span> <b>Nicesnippets</b>";
//display the sting without any html tags
echo strip_tags($html_string);
?>

Output

Welcome to Nicesnippets.com

Example: 2 Userdefined Method

In this example ,you can remove HTML tags using userdefined method.

<?php
//declaring a string using Heredoc method
$string = "<span>Welcome <i>to</i> Nicesnippets.com.</span><b>Hello to everyone Guys </b>";
//calling the remove_html_tags function with the necessary html tags you want to remove
$removed_str=remove_html_tags($string, array("span","b",'i'));
//To avoid executing rest tags it is converted to normal text and display the result
echo htmlentities($removed_str);

    
function remove_html_tags($string, $html_tags) 
{
    $tagStr = "";

  
        foreach($html_tags as $key => $value) 
        { 
            $tagStr .= $key == count($html_tags)-1 ? $value : "{$value}|"; 
        }

  
    $pat_str= array("/(<\s*\b({$tagStr})\b[^>]*>)/i", "/(<\/\s*\b({$tagStr})\b\s*>)/i");
    $result = preg_replace($pat_str, "", $string);
    return $result;
}
?>

Output

Welcome to Nicesnippets.com.Hello to everyone Guys

It Will help you...