Pregマッチングおよび短い文字列での結果の一致のカウント
-
10-07-2019 - |
質問
文字列($ 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)
のようになりますか?
編集カーブボールは申し訳ありませんが、数字と$ itemの間にスペースがある可能性があります。1つのpreg_matchで両方のインスタンスをキャッチできますか?
解決
正規表現で何をしようとしているのかは明確ではありませんが、特定の数値と測定の組み合わせを一致させようとしている場合は、これが役立つ可能性があります:
$count = preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph);
これは、 $ paragraph
で数値と測定値の組み合わせが発生した回数を返します。
EDIT は、 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
所属していません StackOverflow