【问题标题】:Count strpos() Occurences计算 strpos() 出现次数
【发布时间】:2022-01-28 21:46:57
【问题描述】:

如何计算找到的关键字出现次数?目前我有这个

$filesfound = false;
foreach ($arr as $file)
$filesfound = true;
...
echo $vouchers = ($filesfound === true) && (strpos(implode('/', $file), 'Voucher') !== false) ? '<div>+ 2 Files Available</div>' : '';

我正在尝试获取“+2 个可用文件”来实际说明所发现的字符串。我怎样才能做到这一点?多个函数没有给出我期望的结果。在这种情况下,我期望正确读取 2

谢谢!!


解决方案

$filesfound = false;
foreach ($arr as $file) {
   // If occurrences were found. Returns 0 for each match, so we add + 1
   if (strpos(implode('/', $file), 'Voucher') === 0) { 
      $filesfound = true;
      $count = $count + 1; 
   } 
}
echo $count;

【问题讨论】:

  • php.net/manual/en/function.preg-replace.php 是我所知道的唯一可以计数的函数。 strpos 是字符串中的位置,不是字符串的个数。
  • 您是否在文件名中寻找关键字?还是文件内容里面? $arr 中有什么内容?
  • 我会尝试,但是有没有更轻的 CPU 解决方案?我的流量很高,我尽量避免使用正则表达式,除非它的 JS 由客户端的浏览器承担费用。
  • $arr 是使用类解析器在文件数据中找到的键数组,该类解析器从数据库 blob 字段中读取。从那里它内爆并显示文件列表。从那里,我们只需要计算迭代之外包含名称“凭证”的 txt 文件的出现次数。
  • 也许是 substr_count()? php.net/manual/en/function.substr-count

标签: php arrays string count


【解决方案1】:

要计算字符串中某个文本的出现次数,您可以使用:

$text = 'This is a test';
// find how many "is" are within our $text variable:
echo substr_count($text, 'is'); // this will return 2, since there are 2 of "is" in our $text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2012-10-20
    相关资源
    最近更新 更多