blu*_*iel 0 php text count preg-match
我已经有一个函数来计算字符串中的项目数($ paragraph),并告诉我结果是多少个字符,即,当前的tsp和tbsp是7,我可以使用它来计算出该字符串的百分比。
我需要用preg_match加强此效果,因为10tsp应该算作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);
Run Code Online (Sandbox Code Playgroud)
我知道那会是preg_match('#[d]+[item]#', $paragraph)对的吗?
编辑:为弯道球感到抱歉,但是数字和$ item之间可能有空格,一个preg_match可以同时捕获两个实例吗?
对我来说还不太清楚您要使用正则表达式做什么,但是如果您只是想匹配特定的数字量度组合,这可能会有所帮助:
$count = preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph);
Run Code Online (Sandbox Code Playgroud)
这将返回中的数字量度组合的次数$paragraph。
编辑切换为用于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);
Run Code Online (Sandbox Code Playgroud)
执行上面的输出:
字符总数:11
| 归档时间: |
|
| 查看次数: |
1174 次 |
| 最近记录: |