Current Location: Home> Latest Articles> PHP Tips: Efficient Ways to Remove HTML Tags from Strings

PHP Tips: Efficient Ways to Remove HTML Tags from Strings

M66 2025-07-26

Practical Methods to Remove HTML Tags in PHP

In everyday web development, it’s often necessary to extract plain text from HTML content—such as when storing user-submitted data or displaying article previews. PHP provides a couple of simple and efficient methods to achieve this, and in this article, we’ll walk through two common approaches.

Using the strip_tags() Function

PHP’s built-in strip_tags() function is one of the most commonly used solutions. It removes all HTML and PHP tags from a given string.

$string = "<p>This is a string with HTML tags.</p>";
$clean_string = strip_tags($string);
echo $clean_string;
The above code outputs: This is a string with HTML tags. This function also supports a second parameter that allows specific tags to be preserved:

$string = "<p><b>Bold text</b> and <i>italic text</i></p>";
$clean_string = strip_tags($string, '<b>');
echo $clean_string;
This will output: Bold text and italic text. This optional parameter gives you control over which tags should remain in the output.

Using Regular Expressions to Remove HTML Tags

For more customized scenarios, regular expressions can also be used. The preg_replace() function is effective in stripping out HTML tags.

$string = "<div>This is a <div>string with HTML tags</div>.</div>";
$clean_string = preg_replace("/<.*?>/", "", $string);
echo $clean_string;
This code will output: This is a string with HTML tags. Keep in mind that regex might not be as robust as native parsing functions when dealing with deeply nested or malformed HTML, so it's more suitable for simpler use cases.

Best Practices for Use in Development

Whether you're processing user-generated content, building previews, or cleaning up rich text, both of these methods are practical tools. In general, it's recommended to use strip_tags() because it's more reliable and easier to understand, and it allows you to preserve formatting selectively. For specific formatting or structural requirements, regular expressions provide the flexibility needed to customize how the content is cleaned.

Conclusion

Mastering these techniques for removing HTML tags in PHP can significantly improve the quality and reliability of your string processing. Depending on the complexity of the input, choose the method that best suits your project needs to ensure clean, consistent results.