Removing HTML tags by using strip_tag function

$str="Welcome <b>to</b> <i>plus2net</i>";
echo strip_tags($str);
Output
Welcome to plus2net
We can remove all html tags from the content by using strip_tags string function in PHP. This function can be used to collect only the content part without reading the html formatting of the page. Here is the syntax
 strip_tags (input string [, string allowable_tags])
This function also allows one optional string where we can keep the tags which are not to be removed. Say we don't want the hyper links to be removed. So we will allow the linking tag <a href to be kept as it is. Here is the syntax for this.
strip_tags($string_str, '<a>');
In the above code $string_str is the input string.

Using strip_tags function we can collect content from different pages of a directory. Now let us try to collect the content of a sample page test.php. You can read the tutorial on how to collect content of a page here.

Here is the code to collect the content of the page and then we will apply strip_tags to remove all tags and display only the text content without any HML formatting.

$path="test.php";
$contents="";
$fd = fopen ($path, "r"); // opening the file in read mode
while($buffer = fread ($fd,1024)){
$contents .=$buffer;
}
fclose ($fd); 

$contents=strip_tags($contents,'<a>');
echo $contents;

Example: Allowing Specific Tags

$text = '<b>Bold</b> and <i>Italic</i>';
echo strip_tags($text, '<i>');  // Output: Bold and <i>Italic</i>

Example: Using strip_tags() to Prevent XSS

$input = '<script>alert("XSS")</script>Text';
echo strip_tags($input);  // Output: alert("XSS")Text

String Functions nl2br() To add Line break
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Malik

18-07-2009

Thanx dude its worked for me




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer