Search code examples
phpforeachporter-stemmer

Input array and different output after using PorterStemmer in php


I'm using PorterStemmer to stem words just like "working" it will be "work" after calling PorterStemmer class, and it worked for me.

But I want to stem a sentence, for example if I give this sentence to my code:

Before

"I'm playing football and working hard because I have powerful enough"

After

"I'm play football and work hard because I have power enough"

It seems that I have problem with using "foreach" loop in php, because my code is stemming just one word.

My code:

$str=('I am playing football and working hard because I have powerful enough');
$parts = explode(' ', $str);

$word_to_stem = $str;
$stem = PorterStemmer::Stem($word_to_stem);

Now, the $parts included my sentence as an array, how can I stem every word and after that put the new sentence in new variable called $str2


Solution

  • So if you want to stem every word:

    $str=('I am playing football and working hard because I have powerful enough');
    $parts = explode(' ', $str);
    $stemmed_parts = array();
    
    foreach ($parts as $word) {
        $stemmed_word = PorterStemmer::Stem($word);
        $stemmed_parts[] = $stemmed_word;
    }
    
    echo implode(' ', $stemmed_parts);