2009-11-30 137 views
0

我已经有了一个函数来计算字符串中的项目数($ paragraph)并告诉我结果有多少个字符,即tsp和tbsp的当前值是7,我可以用它来计算出该字符串的百分比。Preg匹配并以短字符串计算结果匹配

我需要的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)右算什么?

编辑对于曲线球感到遗憾,但数字和$ item之间可能有空格,一个preg_match可以捕获两个实例吗?

+1

不太清楚你需要什么解析....“tsptbsptbs ...”或“5tbs3tsp ..”?你能举几个例子和预期的结果吗? –

+0

'10tsp'>> 5 || '1tsp'>> 4 || '1茶匙'>> 5 || '1茶匙和2茶匙'>> 10 ||那有意义吗?只是字符数组中的事物的匹配,但也包括之前的数字(有/没有空格) – bluedaniel

回答

4

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

$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

+0

那么我将如何解决在您的preg中已匹配了多少个字符?即'5tsp和10 tsp'//应该是10.那有意义吗? – bluedaniel

+0

你觉得呢? – bluedaniel

+0

我添加了用于计算来自正则表达式匹配的字符数的示例代码。请注意,正则表达式只有一些测量类型...您可能需要添加更适合您的应用程序。另外,如果列表变得很长,您可能需要选择不同的方法,因为您将开始注意到大型正则表达式的性能问题。 – jheddings