我已經有了一個函數來計算字符串中的項目數($ 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可以捕獲兩個實例嗎?
不太清楚你需要什麼解析....「tsptbsptbs ...」或「5tbs3tsp ..」?你能舉幾個例子和預期的結果嗎? –
'10tsp'>> 5 || '1tsp'>> 4 || '1茶匙'>> 5 || '1茶匙和2茶匙'>> 10 ||那有意義嗎?只是字符數組中的事物的匹配,但也包括之前的數字(有/沒有空格) – bluedaniel