如何在 PHP 中编码特殊 HTML 字符

问题描述 投票:0回答:4

在 PHP 中进行 Html 编码最简单的方法是什么?

php html-encode
4个回答
58
投票

通过编码,您的意思是:将所有适用的字符转换为 HTML 实体?

htmlspecialchars
htmlentities

如果您想删除所有 HTML 标签,也可以使用 strip_tags :

strip_tags

注意:这不会阻止所有 XSS 攻击


5
投票

编码.php

<h1>Encode HTML CODE</h1>

<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>

htmlencodeoutput.php

<?php

$code=bin2hex($_POST['inputval']); 
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
 $sublen=$totallen-1;
 $fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";

?> 
<textarea rows='20' cols='100'><?php echo $output?> </textarea> 

你可以像这样编码 HTML 。


2
投票

试试这个:

<?php
    $str = "This is some <b>bold</b> text.";
    echo htmlspecialchars($str);
?>

1
投票

我搜索了几个小时,几乎尝试了所有建议的内容。
这几乎适用于每个实体:

$input = "āžšķūņrūķīš ○ àéò ∀∂∋ ©€ ♣♦ ↠ ↔↛ ↙ ℜ℞";


echo htmlentities($input, ENT_HTML5  , 'UTF-8');

结果:

&amacr;&zcaron;&scaron;&kcedil;&umacr;&ncedil;r&umacr;&kcedil;&imacr;&scaron; &cir; &agrave;&eacute;&ograve; &forall;&part;&ReverseElement; &copy;&euro; &clubs;&diamondsuit; &twoheadrightarrow; &harr;&nrarr; &swarr; &Rfr;&rx;rx;
© www.soinside.com 2019 - 2024. All rights reserved.