2009-11-30 144 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