Search code examples
phpstringtext-extractiondelimited

From a string of comma-delimited phrases, get the first word from each phrase


I have a string, for example:

"abc b, bcd vr, cd deb"

I would like to take the first word of this string until every single point in this case would result in "abc bcd cd". My code unfortunately does not work. Can you help me?

$string = "abc b, bcd vr, cd deb";
$ay = explode(",", $string);
$num = count($ay); 
$ii = 0;
while ($ii != $num) {
    $first = explode(" ", $ay[$ii]);
    echo $first[$ii];
    $ii = $ii+1;
}    

Solution

  • <?php
    function get_first_word($string)
    {
        $words = explode(' ', $string);
        return $words[0];
    }
    
    $string = 'abc b, bcd vr, cd deb';
    $splitted = explode(', ', $string);
    $new_splitted = array_map('get_first_word', $splitted);
    
    var_dump($new_splitted);
    ?>