当前位置:Gxlcms > PHP教程 > PHP如何将HTML字符转义?

PHP如何将HTML字符转义?

时间:2021-07-01 10:21:17 帮助过:57人阅读

PHP如何将HTML字符转义?

在PHP中可以使用“htmlspecialchars()”函数将HTML字符转义,该函数的作用是将特殊字符转换为HTML实体,其用法为“htmlspecialchars($string)”,其参数“$string”代表待转换的字符。

推荐视频教程:《PHP编程从入门到精通(学习路线)》

示例

  1. <?php
  2. $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
  3. echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
  4. ?>
  1. <?php
  2. function fixtags($text){
  3. $text = htmlspecialchars($text);
  4. $text = preg_replace("/=/", "=\"\"", $text);
  5. $text = preg_replace("/&quot;/", "&quot;\"", $text);
  6. $tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
  7. $replacement = "<$1$2$3$4$5$6$7$8$9$10>";
  8. $text = preg_replace($tags, $replacement, $text);
  9. $text = preg_replace("/=\"\"/", "=", $text);
  10. return $text;
  11. }
  12. ?>
  13. an example:
  14. <?php
  15. $string = "
  16. this is smaller < than this<br />
  17. this is greater > than this<br />
  18. this is the same = as this<br />
  19. <a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
  20. <b>Bold</b> <i>italic</i> etc...";
  21. echo fixtags($string);
  22. ?>

推荐教程:《PHP》

以上就是PHP如何将HTML字符转义?的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行