【问题标题】:PHP - mb_strlen, or strlen are returning 0 even though the string is growing in lengthPHP - 即使字符串长度增加,mb_strlen 或 strlen 仍返回 0
【发布时间】:2014-07-22 01:00:51
【问题描述】:

此处对 mb_strlen($str, 'utf-8') 的引用不起作用。

<?php
  function listFolderFiles($dir,$str){
    $ffs = scandir($dir);
    $matches;
    foreach($ffs as $ff){
      preg_match('/(html)$/',$ff,$matches);
      if($ff != '.' && $ff != '..'){
        if(is_dir($dir.'/'.$ff)) {
          $str .= listFolderFiles($dir.'/'.$ff,$str);
        } else if(count($matches) > 0) {
          if (mb_strlen($str, 'utf-8') > 0) {
            $str .= ','.$dir.'/'.$ff;
          } else {
            $str .= $dir.'/'.$ff;
          }
        }
      }
    }
    return $str;
  }
  echo listFolderFiles('index','');
?>

当我 'echo mb_strlen($str,'utf-8)' 我得到正确的长度。

我做错了什么?谢谢。

【问题讨论】:

  • 当 mb_strlen 什么都不做时,$str 是什么?
  • $str 是一个包含文件列表的字符串。 $str 将新文件连接到自身。所以它的长度总是在变化的。
  • 你没有回答我的问题。你回答了你想要的 $str 是什么。在调用mb_strlen 之前添加var_dump($str, mb_strlen($str, 'utf-8')); 然后告诉我们当mb_strlen 返回0 时$str 是什么
  • string(0) "" int(0) string(81) "index/pages/blog/_blog.htmlindex/pages/blog/_blog.htmlindex/pages/blog/_blog.html" int(81) string(109) "index/pages/blog/_blog.htmlindex/pages/blog/_blog.htmlindex/pages/blog/_blog.html,index/pages/home/_home.html" int(109) string(261) "index/pages/blog/_blog.htmlindex/pages/blog/_blog.htmlindex/pages/blog/_blog.html,index/pages/home/_home.htmlindex/pages/blog/_blog.htmlindex/pages/blog/_blog.htmlindex/pages/blog/_blog.html,index/pages/home/_home.html,index/pages/home/_self/images/images_.html" int(261) string(143149) "index/pages/blog/_blog.h...
  • 完美的 mb_strlen 作品

标签: php string for-loop


【解决方案1】:

实际上,连接递归调用导致字符串在每次扫描新目录时重复和连接。所以我删除了$str .= listFolderFiles($dir.'/'.$ff,$str);——它已经修复了

<?php
  function listFolderFiles($dir,$str){
    $ffs = scandir($dir);
    $matches;
    foreach($ffs as $ff){
      preg_match('/(html)$/',$ff,$matches);
      if($ff != '.' && $ff != '..'){
        if(is_dir($dir.'/'.$ff)) {
          $str = listFolderFiles($dir.'/'.$ff,$str);
        } else if(count($matches) > 0) {
          if (strlen($str) == 0) {
            $str .= $dir.'/'.$ff;
          } else {
            $str .= ','.$dir.'/'.$ff;
          }
        }
      }
    }
    return $str;
  }
  echo listFolderFiles('index','');
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多