PHP如何將HTML字元跳脫?

2020-07-16 10:06:29

PHP如何將HTML字元跳脫?

在PHP中可以使用「htmlspecialchars()」函數將HTML字元跳脫,該函數的作用是將特殊字元轉換為HTML實體,其用法為「htmlspecialchars($string)」,其引數「$string」代表待轉換的字元。

推薦視訊教學:《PHP程式設計從入門到精通(學習路線)

範例

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>
<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=""", $text);
$text = preg_replace("/&quot;/", "&quot;"", $text);
$tags = "/&lt;(/|)(w*)( |)(w*)([=]*)(?|(")"&quot;"|)(?|(.*)?&quot;(")|)([ ]?)(/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=""/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href="http://www.example.com/example.php?test=test">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

推薦教學:《PHP

以上就是PHP如何將HTML字元跳脫?的詳細內容,更多請關注TW511.COM其它相關文章!