文字列 ($paragraph) 内の項目数をカウントし、結果が何文字かを示す関数が既にあります。つまり、存在する tsp と tbsp は 7 です。これを使用して、その文字列のパーセンテージを計算できます。
10tsp は 5 としてカウントする必要があるため、preg_match でこれを強化する必要があります。
$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)
右のようなものになることを知っていますか?
EDITカーブボールで申し訳ありませんが、数値と $item の間にスペースがある可能性があります。1 つの preg_match で両方のインスタンスをキャッチできますか?