phpsplitexplodecpu-wordpairwise

Get each word with its next word from a space-delimited string


I want to extract two consecutive words starting from each word in a string.

$string = "This is my test case for an example."

If I explode on each space, I get every word individually, but I don't want that.

[
    'This',
    'is',
    'my',
    'test',
    'case',
    'for',
    'an',
    'example.'
];

What I want is to get each word and its next word including the delimiting space.

Desired output:

[
    'This is'
    'is my'
    'my test'
    'test case'
    'case for'
    'for an',
    'an example.'
]

Solution

  • this will provide the output you're looking for

    $string = "This is my test case for an example.";
    $tmp = explode(' ', $string);
    $result = array();
    //assuming $string contains more than one word
    for ($i = 0; $i < count($tmp) - 1; ++$i) {
        $result[$i] = $tmp[$i].' '.$tmp[$i + 1];
    }
    print_r($result);
    

    Wrapped in a function:

    function splitWords($text, $cnt = 2) 
    {
        $words = explode(' ', $text);
    
        $result = array();
    
        $icnt = count($words) - ($cnt-1);
    
        for ($i = 0; $i < $icnt; $i++)
        {
            $str = '';
    
            for ($o = 0; $o < $cnt; $o++)
            {
                $str .= $words[$i + $o] . ' ';
            }
    
            array_push($result, trim($str));
        }
    
        return $result;
    }