PHP strip_tags() Tutorial 🎯

beginner
9 min

PHP strip_tags() Tutorial 🎯

Welcome to our deep dive into the PHP strip_tags() function! This powerful tool will help you remove HTML and PHP tags from a given string. Let's get started!

Understanding the Basics πŸ“

strip_tags() is a built-in PHP function that removes HTML and PHP tags from a given string, leaving only the text inside the tags. This function is useful when you want to sanitize user input, extract plain text from HTML, or work with text-based data.

Syntax and Usage πŸ’‘

The strip_tags() function takes one argument: the string you want to clean.

php
<?php $html_string = '<p>Hello, World!</p><script>alert("Hello!");</script>'; $plain_text = strip_tags($html_string); echo $plain_text; // Output: Hello, World! ?>

In this example, we have an HTML string with a paragraph and a script tag. By calling strip_tags(), we've removed the unwanted HTML and PHP tags, leaving only the text.

Removing Specific Tags πŸ“

By default, strip_tags() removes all HTML tags, but you can customize the function to remove specific tags or keep certain tags.

php
<?php $html_string = '<p>Hello, World!</p><script>alert("Hello!");</script><div>Keep this tag!</div>'; $allowed_tags = '<div>'; $plain_text = strip_tags($html_string, $allowed_tags); echo $plain_text; // Output: Keep this tag! ?>

In this example, we've set the $allowed_tags variable to only allow the <div> tag. This means all other tags will be removed from the string.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the PHP `strip_tags()` function do?

Practice Exercise 🎯

Use the strip_tags() function to clean the following HTML string:

html
<h1>Welcome to Our Site!</h1> <p>This is some text with <strong>bold</strong> and <a href="https://www.example.com">a link</a></p>

Here's the solution:

php
<?php $html_string = '<h1>Welcome to Our Site!</h1> <p>This is some text with <strong>bold</strong> and <a href="https://www.example.com">a link</a></p>'; $plain_text = strip_tags($html_string); echo $plain_text; // Output: Welcome to Our Site!This is some text with bold and a link ?>

That's it for our PHP strip_tags() tutorial! Now that you understand how to use this function, you can clean up your HTML strings with ease. Happy coding! πŸ’‘