strip_tags()
Introduction
The strip_tags() function in PHP removes HTML and PHP tags from a string, leaving only the plain text content. In this article, we will discuss the function in detail and how it can be used in PHP.
Understanding the strip_tags() function
The strip_tags() function in PHP removes all HTML and PHP tags from the specified string. The syntax for using the function is as follows:
The PHP syntax of the strip_tags()
strip_tags ( string $str [, string $allowable_tags ] ) : stringHere, $str is the string that is being stripped of HTML and PHP tags. The optional parameter $allowable_tags can be used to specify a list of allowed tags that should not be stripped from the string. The function returns the resulting string with all HTML and PHP tags removed.
Example Usage
Let's look at an example to understand the usage of the strip_tags() function in PHP:
Example of PHP strip_tags()
<?php
$str = "<h1>Hello World</h1><p>This is a paragraph.</p>";
$result = strip_tags($str);
echo $result;In the example above, we use the strip_tags() function to remove all HTML and PHP tags from the string. The resulting string Hello WorldThis is a paragraph. is then displayed on the screen using the echo statement.
Using the $allowable_tags parameter
Let's look at another example to understand how the $allowable_tags parameter can be used with the strip_tags() function:
How to use PHP strip_tags()?
<?php
$str = "<h1>Hello World</h1><p>This is a paragraph.</p><a href='https://www.example.com'>Example link</a>";
$result = strip_tags($str, "<a>");
echo $result;In the example above, we use the strip_tags() function to remove HTML and PHP tags from the string. We specify the <a> tag as an allowable tag using the $allowable_tags parameter. As a result, the function removes the <h1> and <p> tags but preserves their text content, while keeping the <a> tag and its content intact. The resulting string Hello WorldThis is a paragraph.<a href='https://www.example.com'>Example link</a> is then displayed on the screen using the echo statement.
Note: strip_tags() does not validate HTML. It simply removes tags based on the provided allowlist, which may leave malformed markup or unclosed tags in the output.
Conclusion
The strip_tags() function is a straightforward tool for extracting plain text from strings containing HTML or PHP markup. By using it, developers can quickly remove unwanted tags while preserving the text content. We hope this article has provided you with a comprehensive overview of the function and how it can be used. If you have any questions or need further assistance, please do not hesitate to ask.
Practice
What is the purpose of the strip_tags() function in PHP?