包子

木森技术分享

路漫漫其修远兮,吾将上下而求索。

您现在的位置是:网站首页 > PHP

php string怎么转为html

2022-04-19 11:36:24461

  php string怎么转为html?

  PHP中字符串与html相互转化函数

  在一般通信过程中,可能会遇到文档文本编码中所不包括很多字符,或者无法在键盘上输入的字符。例如,版权符号(©)、分币符号(¢)和语法重音符号等就属于这种字符。为了克服这些缺点,专门设计了一组统一的按键编码,称为字符实体引用。

  1,htmlentities(),将字符串中特殊字符转化为html实体。

  string htmlentities(string $str,int $quote_style,int $charset,boolean $double_encode),因为标记中引号有特殊意义,可以通过$quote_style参数来选择如何处理引号,其值:ENT_COMPAT,转换双引号,忽略单引号,这是默认值;ENT_NOQUOTES,忽略双引号和单引号;ENT_QUOTES,转换双引号和单引号。$charset参数确定转换所用字符集,如果忽略charset,默认认为ISO-8859-1。$double_encode会阻止htmlentities()对字符串中已有的HTML实体编码。

  如:

<?php
$str = "Bill & 'Steve'";
echo htmlentities($str, ENT_COMPAT); // 只转换双引号
echo "
";
echo htmlentities($str, ENT_QUOTES); // 转换双引号和单引号
echo "
";
echo htmlentities($str, ENT_NOQUOTES); // 不转换任何引号

  输出:

  Bill & 'Steve'

  Bill & 'Steve'

  Bill & 'Steve'

  页面源代码是:

Bill & 'Steve'
Bill & 'Steve'
Bill & 'Steve'   
<?php
$str = "Bill & 'Steve'";
echo html_entity_decode($str, ENT_COMPAT); // 只转换双引号
echo "
";
echo html_entity_decode($str, ENT_QUOTES); // 转换双引号和单引号
echo "
";
echo html_entity_decode($str, ENT_NOQUOTES); // 不转换任何引号

输出:Bill & 'Steve'Bill & 'Steve'Bill & 'Steve'页面源代码是:

Bill & 'Steve'
Bill & 'Steve'
Bill & 'Steve'


  2,htmlspecialchars()函数,将字符串中特殊字符转化为html实体。

  string htmlspecialchars(string $str,int $quote_style,int $charset,boolean $double_encode),参数与htmlentities()函数中参数类似。

  如:

<?php
$str = "This is some  text";
$str1 = htmlspecialchars($str);
echo $str."
";
echo $str1;


  输出:

  This is some bold text

  This is some bold text

  源代码如下:

This is some  text
This is some bold text

htmlspecialchars()函数可以转换的字符列表以及最终转换格式如下:&=>&"(双引号)=>"'(单引号)=>'


  其反函数是htmlspecialchars_decode(),htmlspecialchars_decode(string $str,int $flag),$flags规定翻译表将包含哪种引号以及翻译表用于哪种文档类型,默认是ENT_COMPAT | ENT_HTML401。

  如:

<?php
$str = "This is some  text.";
$str1 = htmlspecialchars_decode($str);
echo $str."
",$str1;


  输出:

  This is some bold text.

  This is some bold text.

  源代码:

This is some bold text.
This is some  text.


  3,strip_tags()函数,从字符串中移除空字符,HTML和PHP标记,将html转化为纯文本。

  string strip_tags(string $str,string $allowable_tags)

  $str,待处理字符串,$allowable_tags指定不被去除的字符列表。

  如:

<?php
$text  =  'Test paragraph. Other text' ;
echo  strip_tags ( $text );
echo  "\n" ;
 
// 允许  和 echo  strip_tags ( $text ,  '' );