Removing HTML Tags in PHP: Using strip_tags and Regular Expressions

This article explains how to strip HTML tags from user‑generated content in PHP by using the built‑in strip_tags function and by applying regular expressions with preg_replace, including code examples, optional tag preservation, and performance considerations.

php Courses
php Courses
php Courses
Removing HTML Tags in PHP: Using strip_tags and Regular Expressions

In web development, it is common to need to clean user‑generated rich‑text content by removing HTML tags and styles that are not suitable for all scenarios.

Method 1: Using the strip_tags function

The PHP built‑in function strip_tags removes HTML tags from a string. Its prototype is:

string strip_tags ( string $str [, string $allowable_tags ] )
$str

is the input string, and $allowable_tags (optional) specifies tags that should be kept, separated by spaces.

Example:

$str = '<p><strong>这是一段富文本内容。 </strong></p>';
echo strip_tags($str); // Output: 这是一段富文本内容。

To preserve certain tags, pass them as the second argument:

$str = '<p><strong>这是一段富文本内容。 </strong></p>';
echo strip_tags($str, '<p><strong>'); // Output: <p><strong>这是一段富文本内容。 </strong></p>

Note that strip_tags only removes HTML tags; it does not affect script or JavaScript code.

Method 2: Using regular expressions

Regular expressions provide a flexible way to strip HTML tags. In PHP you can use preg_replace with a pattern that matches any tag:

$str = "<p><strong>这是一段富文本内容。</strong></p>";
$str = preg_replace('/<[^>]*>/', '', $str);
echo $str; // Output: 这是一段富文本内容。

The pattern '/<[^>]*>/' matches all HTML tags, and preg_replace replaces them with an empty string.

Using regular expressions is more flexible but may have higher performance costs.

Conclusion

Both strip_tags and regular‑expression approaches can remove HTML tags in PHP. strip_tags is simpler and direct, while regex offers greater flexibility for complex scenarios.

The article also lists several PHP learning resources, such as tutorials on Vue3+Laravel8, Vue3+TP6 API development, Swoole, and Workerman+TP6 instant‑messaging systems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Web DevelopmentHTMLregexstrip_tags
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.