开发者

Preg matching and counting the resulting match in a short string

I already have a function that counts the number of items in a string ($paragraph) and tells me how many characters the result is, ie tsp and tbsp present is 7, I can use this to work out the percentage of that string is.

I need to reinforce this with preg_match because 10tsp should count as 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);

I know it would be something like preg_match('#[d]+[item]#', $paragraph) right?

EDIT sorry for the curve ball but there might be a space inbetween the number and the $item, can one preg_match catch both instances?


It's not quite clear to me what you are trying to do with the regex, but if you are just trying to match for a particular number-measurement combination, this might help:

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

This will return the number of times a number-measurement combination occurs in $paragraph.

EDIT switched to use preg_match_all to count all occurrences.

Example for counting the number of matched characters:

$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);

Output from executing the above:

total number of characters: 11

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜