Search code examples
phpdictionaryspell-checking

PHP get words from a word using pspell_check


I had a PHP string which contains English words. I want to extract all the possible words from the string, not by explode() by space as I have only a word. I mean extraction of words from a word.

Example: With the word "stackoverflow", I need to extract stack, over, flow, overflow all of them.

I am using pspell_check() for spell checking. I am currently getting the following combination.

--> sta
--> stac
--> stack
and so on.

So I found the only the words matching stack but I want to find the following words. Notice that I don't want the final word as I've already.

--> stack
--> over
--> flow

My Code:

$myword = "stackoverflow";
$word_length = strlen($myword);
$myword_prediction = $myword[0].$myword[1]; 
//(initial condition as words detection starts after 3rd index)

for ($i=2; $i<$word_length; $i++) {
    $myword_prediction .= $myword[$i];
    if (pspell_check(pspell_new("en"), $myword_prediction)) 
    {
        $array[] = $myword_prediction;
    }
}

var_dump($array);

Solution

  • How about if you have an outer loop like this. The first time through you start at the first character of $myword. The second time through you start at the second character, and so on.

    $myword = "stackoverflow";
    $word_length = strlen($myword);
    
    $startLetter = 0;
    
    while($startLetter < $word_length-2 ){
        $myword_prediction = $myword[$startLetter] . $myword[$startLetter +1];
        for ($i=$startLetter; $i<$word_length; $i++) {
            $myword_prediction .= $myword[$i];
            if (pspell_check(pspell_new("en"), $myword_prediction)) {
                $array[] = $myword_prediction;
            }
        }
    $startLetter ++;
    }