[英]PHP htmlspecialchars() or htmlentities() with exception
如何為htmlspecialchars()
或htmlentities()
定義異常? 我想將所有特殊字符轉換為 HTML 安全,除了<strong><b><i><em><br>
最簡單的方法是使用htmlentities
轉換您的字符串,然后使用preg_replace替換選定的標簽:
<?php
$string = '<p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>';
$encoded_string = htmlentities($string);
$encoded_string = preg_replace('/<(\/?(strong|b|i|em|br))>/', '<$1>', $encoded_string);
echo($encoded_string);
//outputs: <p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>
當然,如果您也想在標簽內處理 arguments,那么正則表達式模式需要一些工作,盡管這些標簽通常缺少任何參數。
我通過添加另一個(.?\/)?
保留<br>
和<br />
(盡管將它們都轉換為<br>
):
/<(\/?(strong|b|i|em|br))(.?\/)?>/i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.