首页 > 解决方案 > 如何计算由 . 在一个大字符串中?

问题描述

我需要在一个大字符串中计算一个段中出现的次数,以“。”结尾,并对字符串中的所有段执行此操作。

例如,如果我在 $str 变量中得到这个:

Manual Testing is a type of Software Testing where Testers following are few common myths and facts related to testing. Manual Testing is the most primitive of all testing types and helps find bugs in the software system. Manual Testing is a type of Software Testing where Testers manually execute test cases without using any automation tools. Manual Testing is the most primitive of all testing types and helps find bugs in the software system. 

预期的输出将是:

"There is 1 occurrence in your string"

因为重复的一段是字符串,所以我想用“。”来爆炸我的str。作为分隔符,然后使用此功能:

substr_count ( string $haystack , string $needle)

对此有什么想法吗?

谢谢 !

标签: phpstringcount

解决方案


<?php

$str = 'Manual Testing is a type of Software Testing where Testers following are few common myths and facts related to testing. Manual Testing is the most primitive of all testing types and helps find bugs in the software system. Manual Testing is a type of Software Testing where Testers manually execute test cases without using any automation tools. Manual Testing is the most primitive of all testing types and helps find bugs in the software system. Manual Testing is a type of Software Testing where Testers manually execute test cases without using any automation tools.Manual Testing is a type of Software Testing where Testers manually execute test cases without using any automation tools. Manual Testing is a type of Software Testing where Testers following are few common myths and facts related to testing.';

$segment_data = array_count_values(array_map("trim",array_slice(explode(".",$str),0,-1)));

$occurrences = array_sum($segment_data) - count($segment_data);

echo "There are $occurrences occurrence(s) in your string";

演示: https ://3v4l.org/eMcNX

  • 我们首先根据 period( .) 分隔符分解字符串。然后,我们执行array_slice()来避免在末尾找到空字符串。然后,我们在array_map()的帮助下修剪()它以使段更好,以应用于分解的字符串数组中的每个段。

  • 现在,在array_count_values()的帮助下,我们得到了每个段的出现次数。

  • 我们做一个array_sum来对所有段的所有出现求和,然后从唯一段本身的大小中减去它以获得编号。根据需要重复出现。


推荐阅读