twharmon
twharmon

Reputation: 4272

How do I count the number of times a (foreign) word occurs in a string?

I got this to work in English just fine, but it's not working for other languages.

$lemma = "का";
$text = 'उस का नाम रवि है। काम का समय आ गया।';
$pattern = '/\b' . $lemma . '\b/';
$hits = preg_match_all($pattern, $text, $matches);

$hits should be 2 in this example. I found several related questions about using '\u' or something, but was unable to make it work.

----- Edit The example above doesn't seem to have enough text, so I made it longer to better test the solutions.

$lemma = "में";
$text = 'पेत्रउस्कास इवाल्डैस ने लाइटवेट कैटेगरी में लंदन ओलंपिक 2012 में कांस्य पदक जीता था. मनोज कुमार लंदन ओलंपिक में भी खेले थे लेकिन वो क्वार्टर-फ़ाइनल में अपनी जगह नहीं बना सके थे. मनोज ने ताजीकिस्तान राखिमॉव शाक्वाकात्झॉन को एआईबीए वर्ल्ड ओलंपिक क्वालिफ़िकेशन में हराकर रियो ओलंपिक में प्रवेश पाया था. इससे पहले रियो ओलंपिक में 75 किलो भार वर्ग में भारतीय मुक्केबाज़ विकास कृष्ण यादव ने प्री क्वार्टर फ़ाइनल में जगह बना ली है. गुरुवार को 56 किलो भार वर्ग में मुक्केबाज़ शिवा थापा रियो ओलंपिक में अपना पहला मुकाबला खेलने के लिए रिंग में उतरेंगे. मनोज कुमार का अगला मुकाबला रविवार को प्री-क्वार्टर फ़ाइनल में उज़्बेकिस्तान के फ़ज़लीद्दीन ग़ैब्नाज़रॉफ से होगा.';
$pattern = '/\b('.$lemma.')\b/';
$hits = preg_match_all($pattern, $text, $matches);
echo count($matches);

"में" should give 13, and "ली" should give 1.

Upvotes: 2

Views: 58

Answers (2)

twharmon
twharmon

Reputation: 4272

I found a solution based on @Zeus's answer. It seems to work for everything I put in it. I may have to add to /[\s.,\"\']+/ to make sure everything works.

$hits = 0;

foreach($documents as $document){
    $text = $document->getText();
    $words = preg_split("/[\s.,\"\']+/", $text);

    foreach ($words as $word) {
        if ($word == $lemma) {
            $hits++;
    }
}

Upvotes: 0

user5232258
user5232258

Reputation:

Using foreach and explode

$lemma = "का";
$text = 'उस का नाम रवि है। काम का समय आ गया।';

function findOccurings($text, $search) {
    $words = explode(' ', $text);

    $times = 0;
    foreach ($words as $word) {
        if ($word == $search) {
            $times++;
        }
    }
    return $times;
}

var_dump(findOccurings($text, $lemma));

// Output: int(2)

Upvotes: 1

Related Questions