Preg匹配和计算结果匹配在一个短字符串 [英] Preg matching and counting the resulting match in a short string

查看:111
本文介绍了Preg匹配和计算结果匹配在一个短字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个函数计算字符串中的项目数($段),并告诉我结果是多少字符,即tsp和tbsp目前是7,我可以使用这个来计算出的百分比字符串是



我需要通过preg_match强化这一点,因为10tsp应该计为5。

  $ characters = strlen($ paragraph); 
$ items = array(tsp,tbsp,tbs);
$ count = 0;

foreach($ items as $ item){

//计算段落中的格式化次数
$ countitems = substr_count($ paragraph, $ item);
$ countlength =(strlen($ item)* $ countitems);

$ count = $ count + $ countlength;
}

$ overallpercent =((100 / $ characters)* $ count);

我知道它会像 preg_match('#[d] [item]#',$ paragraph)对不对?



EDIT

解决方案

这不清楚我是什么正试图用正则表达式,但如果你只是想匹配一个特定的数字测量组合,这可能有助于:

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

这将返回 $中出现数字测量组合的次数



计算匹配字符数的示例:

  $ 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\\\
,$ charcnt);

执行上述输出:


总字符数:11



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

这篇关于Preg匹配和计算结果匹配在一个短字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆