php htmlspecialchars() and strip_tags functions both format HTML codes. Many people think that the functions of htmlentities and htmlspecialchars are the same, but are they really the same? The answer is no, otherwise it would not be the case. There are two functions. This article will take you to understand the difference between php htmlspecialchars() and strip_tags function
First let’s take a look at the usage examples of htmlspecialchars function and strip_tags function:
<?php $str="<a href='http://www.php.cn'>php中文网</a>"; echo htmlspecialchars($str); echo "<br><br>"; echo strip_tags($str); ?>
The code runs the browser output result:
#View the page source code, the result is as follows:
<a href='http://www.php.cn'>php中文网'"</a><br/><br/>php中文网'"
It can be seen from the result that htmlspecialchars() and strip_tags The difference is as follows:
Difference 1:
strip_tags function is used to remove HTML tags, while htmlspecialchars does not remove html tags, but only converts tags into HTML instances, so the maximum between the two The difference is that one is to delete the HTML tags, and the other is to convert the html tags into other characters.
Difference 2:
If the tags in the string that need to be removed from the HTML tags are originally wrong, for example, the greater than symbol is missing, an error will be returned when using the strip_tags function, while htmlspecialchars does not There will be errors after converting to HTML entities.
Difference 3:
When preventing XSS attacks, it is generally recommended to use the htmlspecialchars function, because although strip_tags can delete HTML tags, it will not delete " or '. So even if you use strip_tags , you still need to use the htmlspecialchars function to filter out " or '
in form submission or user message board. If you want the original data output to be taken to the browser, then please use the htmlspecialchars function instead of the strip_tags function.
[Related article recommendations]
A brief introduction to the htmlspecialchars, strip_tags, and addslashes functions in php
php Remove string tags strip_tags( ) Detailed explanation of function examples
The above is the detailed content of The difference between php htmlspecialchars() and strip_tags functions. For more information, please follow other related articles on the PHP Chinese website!