【问题标题】:Counting length of string with HTML numbered entities in PHP用PHP中的HTML编号实体计算字符串的长度
【发布时间】:2012-01-31 20:53:56
【问题描述】:

我想用 PHP 计算字符串的长度。该字符串包含 HTML 实体编号,它会增加计数的字符数:破折号是 –,当我只希望它计为 1 时,它计为 7。

如何将html编号的实体转换为特殊字符只计算长度为1的形式?

示例字符串:

Goth-Trad – ‘Cosmos’

代码:

$string = html_entity_decode('Goth-Trad – ‘Cosmos’');
    echo strlen($string);

当我在寻找“20”时产生“38”。出了什么问题?

【问题讨论】:

  • 即使你使用了htmlentities 标签,你没看到php.net/htmlentitiesSee Also部分
  • 不幸的是,文档没有为我提供我正在寻找的结果,这就是我在 SO 上发布问题的原因。如果您在不了解问题背景的情况下不立即投反对票,我将不胜感激。

标签: php html-entities strlen


【解决方案1】:

只需解码它并计算解码的一个吗?

$string = html_entity_decode("Goth-Trad – ‘Cosmos’",ENT_QUOTES,"UTF-8");
echo strlen($string);

【讨论】:

  • 不幸的是,这个确切的代码片段仍然产生 38,而应该是 20。知道可能出了什么问题吗?
  • @Sqrler 你是对的,我刚刚尝试过,php 函数无法解码实体。不过,代码是正确的。我会调查这个问题
  • @Damien,谢谢!下面的彼得刚刚更新了他的答案,这产生了我正在寻找的结果。再次感谢您的回答!
  • @Sqrler 将编码设置为 UTF-8 看起来像解决问题?不过我得到了 26,请看这里codepad.org/iizpEyVX
  • @Sqrler DAmn,我太慢了 :)
【解决方案2】:

你可以用这个:

$html = 'Goth-Trad – ‘Cosmos’';
echo strlen(utf8_decode(html_entity_decode($html, ENT_COMPAT, 'utf-8')));

【讨论】:

  • 不幸的是,与上面的注释相同:这段代码产生 38,而应该是 20。知道可能出了什么问题吗?
  • @PeterKrejci 不错,比我快几分钟!
  • 我看到 utf8_decode() 将破折号和撇号转换为问号。我该如何避免呢?
【解决方案3】:

请尝试以下编码功能:

<?php   

$string='Goth-Trad &#8211; &#8216;Cosmos&#8217;'; 

echo html_entity_text_length($string); // Calling the function 

//html_entity_text_length function start

function html_entity_text_length($string){
    preg_match_all("/&(.*)\;/U", $string, $pat_array);
    $additional=0;
    foreach ($pat_array[0] as $key => $value) {
       $additional += (strlen($value)-1);
    }

    $limit+=$additional;
    return  strlen($string)-$limit;
}

//html_entity_text_length function end

?>

【讨论】:

  • 升级答案。不澄清
  • 这是一个代码转储.. 你能把它变成一个正确的答案吗?如果没有,它可能会被删除。查看其他问题的其他答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多