【问题标题】:Count number of chars excluding newlines [closed]计算不包括换行符的字符数[关闭]
【发布时间】:2014-11-22 17:35:25
【问题描述】:

我正在使用 strlen() 来计算文本中的字符数,但它甚至可以计算换行符 \n。我可以替换换行符以使 strlen() 不计算它们吗?

【问题讨论】:

  • 考虑在您的问题中添加代码 ;) 对于您的问题,您可以将字符串复制到一个临时字符串,从中删除换行符,然后计算此临时字符串中的字符数
  • strlen(str_replace("\n", "", $str));

标签: php newline strlen chars


【解决方案1】:

首先用null替换所有new line character,然后计算长度。

echo strlen(str_replace(array("\n", "\r\n", "\r"), '', $string));

【讨论】:

    【解决方案2】:
    <?php
    $string = "Testing \n testing";
    
    
    $x = strlen(str_replace(array("\n","\r","\r\n"), "", $string)); //replace '\n \r' with nothing before counting the rest        
    

    【讨论】:

      【解决方案3】:

      你可以减去一个,像这样:

      $x = stlen(str);
      $x--;
      

      【讨论】:

      • 如果字符串中有 X 个 "\n" 怎么办
      • 然后用 if(strlen(str) == 1) ... 或 if(str == "\n") ... 进行检查
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多