Hello Friends Today, through this tutorial, I will tell you How do you remove all HTML tags from a string in PHP With Example? You can remove all HTML tags from a string in PHP using regular expressions. Here’s a simple example:
<?php // Example string with HTML tags $string = '<p>This is <b>bold</b> and <i>italic</i> text.</p>'; // Remove HTML tags using regular expression $clean_string = preg_replace('/<[^>]*>/', '', $string); // Output cleaned string echo "Original string: $string <br>"; echo "Cleaned string: $clean_string"; ?>
In this example:
1. We have a string `$string` that contains HTML tags `<p>`, `<b>`, and `<i>`.
2. We use the `preg_replace()` function with a regular expression `/<[^>]*>/` to match and replace all HTML tags with an empty string.
3. The cleaned string is stored in the variable `$clean_string`.
4. We then output both the original and cleaned strings using `echo`.
Output:
Original string: <p>This is <b>bold</b> and <i>italic</i> text.</p> Cleaned string: This is bold and italic text.
This regular expression `<[^>]*>` matches any substrings that start with `<` and end with `>`, effectively removing all HTML tags and leaving only the text content. However, this approach may not handle all edge cases perfectly, especially complex HTML structures. For more robust HTML parsing, you might consider using dedicated HTML parsing libraries like DOMDocument or SimpleXML.