0

文字列 ($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 で両方のインスタンスをキャッチできますか?

4

1 に答える 1

5

正規表現で何をしようとしているのかはよくわかりませんが、特定の数値と測定の組み合わせに一致させようとしているだけなら、これが役立つかもしれません:

$count = preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph);

これは、数値と測定値の組み合わせが で発生する回数を返します$paragraph

EDITpreg_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

于 2009-11-30T22:57:02.133 に答える