Home >Backend Development >PHP Tutorial >Detailed explanation of the usage of PHP's strip_tags() function
Detailed explanation of the usage of PHP's strip_tags() function
In PHP programming, the strip_tags() function is one of the very useful functions. It can help us remove HTML and PHP tags, leaving only plain text content. In this article, we will explain the usage of strip_tags() function in detail and provide some useful examples.
The basic syntax of the strip_tags() function is as follows:
strip_tags(string $str, string $allowed_tags = null): string
Among them, the $str parameter is the string to be removed, and the $allowed_tags parameter is optional. It is used to specify the string that is allowed to be retained. HTML markup. If the $allowed_tags parameter is not specified, the function will strip all HTML and PHP tags.
Now, let’s look at some examples.
Example 1: Remove HTML tags
In this example, we will demonstrate how to remove HTML tags using the strip_tags() function.
<?php $str = "<div><p>Hello, world!</p></div>"; echo strip_tags($str); ?>
The output result is:
Hello, world!
In this example, we create a string containing HTML tags, and then call the strip_tags() function to remove the tags. The output result only retains the text content, that is, "Hello, world!".
Example 2: Keep specified HTML tags
In this example, we will demonstrate how to use the $allowed_tags parameter to specify HTML tags to keep.
<?php $str = "<div><p>Hello, <b>world</b>!</p></div>"; echo strip_tags($str, "<p><b>"); ?>
The output is:
<p>Hello, <b>world</b>!</p>
In this example, we create a string containing HTML tags, then call the strip_tags() function and use the $allowed_tags parameter to specify the HTML tags to retain . The output only retains the "e388a4556c0f65e1904146cc1a846bee" and "" tags, and the remaining tags are removed.
Example 3: Keep specified PHP tags
In this example, we will demonstrate how to remove HTML tags and PHP tags using the strip_tags() function.
<?php $str = "<div><p>Hello, <?php echo 'world'; ?></p></div>"; echo strip_tags($str, "<p>"); ?>
The output is:
<p>Hello, world</p>
In this example, we create a string containing HTML tags and PHP tags, then call the strip_tags() function and use the $allowed_tags parameter to specify what to keep HTML markup. Since we didn't specify to keep the PHP tags, they were removed as well.
Summary
The strip_tags() function is a very useful function, it can help us remove HTML and PHP tags, leaving only plain text content. You can use the $allowed_tags parameter to specify HTML tags to preserve. In actual development, we can combine regular expression, SANITIZE-HTML and other methods to ensure code security.
The above is the detailed content of Detailed explanation of the usage of PHP's strip_tags() function. For more information, please follow other related articles on the PHP Chinese website!