PHP regular expression is a powerful tool that can be used to process various patterns and rules in text. In web development, we often encounter the need to remove HTML tags, such as filtering out HTML tags from user input, or extracting plain text from web content. This tutorial will introduce how to use PHP regular expressions to remove HTML tags and give specific code examples.
In PHP, you can use regular expressions to match and replace HTML tags. Here is a simple example that demonstrates how to remove HTML tags from text:
$text = "Hello, World!
"; $clean_text = preg_replace("/<.*?>/", "", $text); echo $clean_text;
In this example, we use thepreg_replace
function to replace all HTML tags in the text. The regular expression/<.*?>/
matches any HTML tag and replaces it with an empty string, achieving the effect of removing HTML tags.
Sometimes we may only want to remove specific HTML tags, while retaining other tags and text content. The following example shows how to remove theand
tags:
$text = "Hello, !
"; $clean_text = preg_replace("/|