【问题标题】:PHP strlen on speech marks and commas语音标记和逗号上的 PHP strlen
【发布时间】:2016-06-15 11:38:21
【问题描述】:

我有以下长度为 78 个字符的字符串:

PlayStation VR Available ‘April 2016’, According To VR Production Company Site

当我对这个字符串执行 PHP 函数 strlen 时,它给我的值是 90。

    $title_lenth = strlen($the_title);
    echo $title_lenth; // 90

我认为这是因为 strlen 使用了语音标记和逗号的 html 实体,这将导致字符数为 5 个字符而不是 1 个。

如何告诉strlen 将标点符号计为一个字符?

我已经尝试过使用mb_strlen,但它返回的值相同。

谢谢

【问题讨论】:

  • 你不能像那样改变 strlen() 的行为,strlen() 返回字符串中的字节数,一个 html 实体包含几个字节......你需要什么首先是使用 html_entity_decode() 之类的东西将该实体转换为字符,然后使用 strlen() 或 mb_strlen()
  • 只是好奇 - 你使用的是什么版本的 PHP?我正在使用 5.6.19,当同时使用 strlenmb_strlen 时,我得到了 78 的预期结果。
  • 在我的情况下,它在使用 strlen 和 mb_strlen 时给出 82
  • @mark - 感谢您的提示 - 但是,这已将其减少到 82 - 所以仍然不是预期的 78
  • @brandon - 我使用的是 5.5.3,所以可能是 PHP 问题?

标签: php string strlen


【解决方案1】:

看起来旧 PHP 版本的行为有所不同。 PHP 5.5.3 是个问题。

我解决了以下问题:

    $the_title =  html_entity_decode(get_the_title());
    $the_title = utf8_decode($the_title);
    $title_lenth = strlen($the_title);

这是导致问题的非 utf8 引号。

【讨论】:

    【解决方案2】:
    $the_title = "PlayStation VR Available ‘April 2016’, According To VR Production Company Site";
    $title_lenth = strlen(utf8_decode($the_title));
    echo $title_lenth; // 78
    exit;
    

    正如 php.net http://php.net/manual/de/function.strlen.php#45407 上的 cmets 所建议的那样

    【讨论】:

      【解决方案3】:
      $str = "PlayStation VR Available ‘April 2016’, According To VR Production Company Site";
      $str1 = str_replace(' ', '', $str);
      $title_lenth = strlen($str1);
      echo $title_lenth;
      

      这会将字符串长度减少到 72

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-14
        • 2012-09-10
        • 2020-02-12
        • 1970-01-01
        相关资源
        最近更新 更多