dsx5201 2010-08-09 16:53
浏览 12
已采纳

在php中计算字符

I want to count how many characters a certain string has in PHP, but I cant get it to work.

I did a var_dump and this is what I got:

string(23) "Children’s Center"

It seems like ' gets translated to ’s

This makes it impossible to get the actual character count. I tried using html_entity_decode but it did not help.

Anyone?

EDIT: My function looks like this now:

function make_shorter($string, $maxlength)
{
 $string = stripslashes($string);   
 $string = html_entity_decode($string);
 if ( mb_strlen(utf8_decode($string)) > $maxlength)
  return substr($string,0,$maxlength).'...';
 else
  return $string;
}

I can't change how the data gets in to the system. I can only modify it's output.

(It's a wordpress site)

  • 写回答

4条回答 默认 最新

  • drlma06060 2010-08-09 17:12
    关注

    It seems like ' gets translated to ’s

    That's the HTML character reference for the single right smart-quote, , which some people also use to represent an apostrophe (especially those typing in MS Word). At some prior point in your processing, something has applied htmlentities() to your data.

    HTML-escaping should only be carried out at the output stage, when inserting text into an HTML page. So look back and see if you've got a function doing something stupid like calling htmlentities() over every entry in the $_POST/$_GET/$_REQUEST array. This is a common but completely bogus way to try to prevent XSS attacks. If you see it, you are at some point going to need to take it out and go through your templates adding proper HTML-escaping around every time you drop a variable into HTML.

    Either way, use htmlspecialchars() instead of htmlentities() and it'll leave the non-ASCII characters like alone.

    html_entity_decode() definitely should undo the above encoding, leaving you with a raw string. might still count as either one or two bytes, though, depending on what encoding you decode into. If you want to count characters properly and you have UTF-8 strings, you will need mb_strlen().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题