Preg는 짧은 문자열로 결과 일치 및 계산
-
10-07-2019 - |
문제
이미 문자열 ($ 단락)의 항목 수를 계산하는 함수가 있고 결과가 얼마나 많은 문자인지 알려줍니다. 즉, 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)
오른쪽?
편집하다 커브 볼에 대해 죄송하지만 숫자와 $ 항목 사이에 공간이있을 수 있습니다. 하나의 preg_match가 두 인스턴스를 모두 잡을 수 있습니까?
해결책
REGEX로 무엇을하려고하는지는 확실하지 않지만 특정 숫자 측정 조합에 맞는 경우 도움이 될 수 있습니다.
$count = preg_match_all('/\d+\s*(tbsp|tsp|tbs)/', $paragraph);
이것은 숫자 측정 조합이 발생하는 횟수를 반환합니다. $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);
위의 실행에서 출력 :
총 문자 수 : 11
제휴하지 않습니다 StackOverflow