views:

195

answers:

1

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?

+3  A: 

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

jheddings
so how would i work out how many characters have been matched in your preg? ie '5tsp and 10 tsp' //should be 10. does that make sense?
bluedaniel
what do you think?
bluedaniel
I added sample code for counting the number of characters in the matches from the regex. Note that the regex only has a few measurement types... You might need to add more suitable for your application. Also, if the list becomes very long, you might want to choose a different approach, as you will start to notice performance problems with a large regex.
jheddings
man oh man youve really gone and done it!! mate you've helped me out like you wouldnt even believe! Seriously I gotta send you a christmas present for this!
bluedaniel
Glad it was helpful... I'll be interested to see how it pops up on your site. I've already sent it to my wife, so we'll be watching ;)
jheddings