我已经有一个统计的项目数在一个字符串($段),并告诉我结果多少个字符是,即TSP和汤匙现在是7,我可以用它来制定的,该百分比的函数字符串是

我需要的preg_match加强这种因为10tsp应5计数。

$characters = strlen($paragraph);
$items = array("tsp", "tbsp", "tbs");
    $count = 0;

        foreach($items as $item) {

            //Count the number of times the formatting is in the paragraph
            $countitems = substr_count($paragraph, $item);
            $countlength= (strlen($item)*$countitems);

            $count = $count+$countlength;
        }

    $overallpercent = ((100/$characters)*$count);

我知道这会是这样的preg_match('#[d]+[item]#', $paragraph)吧?

修改作为弧线球抱歉,但有可能是其间数的空间和$项目,可一个的preg_match赶上这两种情况?

有帮助吗?

解决方案

这不是很清楚,我你正在尝试用正则表达式的事,但如果你只是想匹配特定数量的测量组合,这可能帮助:

$count = preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph);

这将返回在某一个数字测量组合的次数$paragraph

修改切换到使用preg_match_all计数所有出现。

实施例,用于计算匹配的字符数:

$paragraph = "5tbsp and 10 tsp";

$charcnt = 0;
$matches = array();
if (preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph, $matches) > 0) {
  foreach ($matches[0] as $match) { $charcnt += strlen($match); }
}

printf("total number of characters: %d\n", $charcnt);

从执行输出上述:

  

字符的总数:11

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top