Home > Backend Development > PHP Tutorial > How to remove HTML tags in PHP using regular expressions

How to remove HTML tags in PHP using regular expressions

WBOY
Release: 2023-06-22 17:08:01
Original
949 people have browsed it

In web development, HTML is an essential element. But sometimes we need to extract plain text from HTML without HTML tags. At this time, regular expressions are a very convenient tool.

In PHP, you can use the preg_replace() function to remove HTML tags. The usage of this function is as follows:

preg_replace($pattern, $replacement, $subject);
Copy after login

Among them, $pattern is the regular expression pattern, $replacement is the replacement string, and $subject is the string to be processed. Note that both $pattern and $replacement can be arrays, as discussed below.

Next, we will discuss several common regular expressions for removing HTML tags.

  1. Remove HTML tags
$pattern = '/<[^>]*>/';
$replacement = '';
$text = preg_replace($pattern, $replacement, $html);
Copy after login

In this regular expression, < represents the left angle bracket, 1 represents Matches any character except the right angle bracket, * means match 0 or more times. Therefore, this expression will match any HTML tag and replace it with the null character.

  1. Remove script tags
$pattern = '/<script[^>]*>(.*?)</script>/is';
$replacement = '';
$text = preg_replace($pattern, $replacement, $html);
Copy after login

This regular expression will match any text with a

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template