In this article, we will learn how to remove HTML tags from a string in PHP Using strip_tags() PHP Function also we will make the user-defined function to remove tags from the string.
it is useful to sanitize the string Lets understand by example:
strip_tags()
strip_tags() to remove tags from string
index.php
<?php
/*
make string with html tags
no problem if have multiple tags
*/
$str="Hello, <b>PHP Developers</b>";
$str2="welcome to <br> <p>Rathorji PHP Tutorial!</p>";
//remove tags
strip_tags($str);
//allow tags
strip_tags($str, '<br>');
//allow multiple tags tags
strip_tags($str2, ['br', 'p']);
?>
Custom Function
user-defined function to remove tags
index.php
<?php
function remove_tags($string, $html_tags) {
$html_str = "";
foreach ($html_tags as $key => $value) {
$html_str .= $key == count($html_tags) - 1 ? $value : "{$value}|";
}
$pat_str = array("/(<\s*\b({$html_str})\b[^>]*>)/i", "/(<\/\s*\b({$html_str})\b\s*>)/i");
return preg_replace($pat_str, "", $string);
}
//String with html tags
$str = "welcome to <br> <p>Rathorji PHP Tutorial!</p>";
//call the function
echo remove_tags($str, array("br", "p"));
?>
Output:
welcome to Rathorji PHP Tutorial!