How to remove HTML tags from a string in PHP?
In this article, we will discuss how to remove HTML tags from a string in PHP. Removing HTML tags can be done in 2 ways-
- Using predefined method
- Using the userdefined method
Predefined method: Remove HTML tag in PHP
In PHP, strip_tags() method removes the existing HTML tags.
Syntax:-
strip_tags(string);
Example:-
<?php //declaring a string with html tags $html_string="Welcome <span>to</span> <b>Codespeedy</b>"; //display the sting without any html tags echo strip_tags($html_string); ?>
Output:-
Welcome to Codespeedy
User-defined method for removing HTML tag in PHP
Let us discuss our user-defined method that takes the number of HTML tags as input for removing those tags.
<?php //declaring a string using Heredoc method $html_string = <<<STRING <html> <body> <span>Welcome to Codespeedy.</span> <b>Hello to everyone</b> </body> </html> STRING; //calling the remove_html_tags function with the necessary html tags you want to remove $removed_str=remove_html_tags($html_string, array("html", "body", "span","b")); //To avoid executing rest tags it is converted to normal text and display the result echo htmlentities($removed_str); function remove_html_tags($html_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, "", $html_string); return $result; } ?>
Output:-
Welcome to Codespeedy. Hello to everyone
Note:-
- This user-defined method only removes those HTML tags that are passed as an argument.
In this way, we can remove HTML tags in PHP. If you have any doubts about the above topic, leave us a comment below.
See also,
Leave a Reply