开发者

PHP & word counting from string

开发者 https://www.devze.com 2023-02-19 14:11 出处:网络
Trying to take numbers from a text file and see how many times they occur. I\'ve gotten to the point where I can print all of them out, but I want to display just the number once, and then maybe the o

Trying to take numbers from a text file and see how many times they occur. I've gotten to the point where I can print all of them out, but I want to display just the number once, and then maybe the oc开发者_StackOverflow中文版currences after them (ie: Key | Amount; 317 | 42). Not looking for an Answer per se, all learning is good, but if you figure one out for me, that would be awesome as well!


preg_match_all will return the number of matches against a string.

$count = preg_match_all("#$key#", $string);
print "{$key} - {$count}";


So if you're already extracting the data you need, you can do this using a (fairly) simple array:

$counts = array();

foreach ($keysFoundFromFile AS $key) {
    if (!$counts[$key]) $counts[$key] = 0;
    $counts[$key]++;
}

print_r($counts);

If you're already looping to extract the keys from the file, then you can simply assign them directly to the $counts array without making a second loop.


I think you're looking for the function substr_count().
Just a heads up though, if you're looking for "123" and it finds "4512367" it will match it as part of it. The alternative would be using RegEx and using word boundaries:

$count = preg_match_all('|\b'. preg_quote($num) .'\b|', $text);

(preg_quote() for good practice, \b for word boundaries so we can be assured that it's not a number embedded in another number.)

0

精彩评论

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