PHP strip_tags() Function

Quick summary: The PHP strip_tags() function removes HTML and PHP tags from a string.

PHP strip_tags() Syntax

strip_tags(string $string, array|string|null $allowed_tags = null): string
PHP

PHP strip_tags() Basic examples

echo strip_tags("<b>Hello</b> world");
PHP
Output:
Hello world

Removes HTML tags from a string.

PHP strip_tags() Real-world usage

$html = "<p>Hello <strong>world</strong></p>";
echo strip_tags($html);
PHP
Output:
Hello world

Extracts plain text from HTML content.

PHP strip_tags() Edge cases

echo strip_tags("<p>Hello</p><br>", "<br>");
PHP
Output:
Hello<br>

Allows specific tags to remain.

PHP strip_tags() Common mistakes

Using strip_tags for security

strip_tags does not prevent XSS.

Incorrect
echo strip_tags($_POST['input']);
Correct
echo htmlspecialchars($_POST['input']);

Use proper escaping instead of stripping tags.

PHP strip_tags() Frequently Asked Questions

What does strip_tags() do in PHP?

strip_tags() removes HTML and PHP tags from a string.

Can strip_tags() allow certain HTML tags?

Yes, you can specify allowed tags as a second parameter.

Is strip_tags() safe for XSS protection?

No, it is not sufficient alone for preventing XSS attacks.

Does strip_tags() modify the original string?

No, it returns a cleaned string.

What happens to attributes in strip_tags()?

All attributes are removed along with the tags.

Can strip_tags() remove script tags?

Yes, but malicious content may still remain if not properly sanitized.

What is the difference between strip_tags() and htmlspecialchars()?

strip_tags() removes tags, while htmlspecialchars() escapes them.

Does strip_tags() handle nested tags?

Yes, it removes all tags regardless of nesting.

Can strip_tags() be used for cleaning HTML?

It can help, but is not a full HTML sanitizer.

What is a real-world use case of strip_tags()?

Cleaning user input before storing or displaying plain text.

Does strip_tags() affect text content?

It preserves text while removing tags.

Should strip_tags() be used alone for security?

No, combine it with proper validation and escaping.

PHP strip_tags() Related PHP Functions