skip to Main Content

This script works fine by getting the values of each first word in a sentence Eg.(Ann and Mike). My issue is that the output of an array is not what I want.

I was expecting $result_names = array("Ann","Mike"); but I got

Array ( [0] => Ann [1] => Ann Mike )

Here is the Code

$names = array();

$str = 'Ann is good,"Mike loves cooking"';
$result = explode(',',$str); //parsing with , as delimiter 
$op = "";
foreach($result as $value)
{
    $tmp = explode(' ',$value);
    $op .= trim($tmp[0],"'"")." ";

 $names[] = $op;

}
$op = rtrim($op);
$rr = ucwords($op);


print_r($names);

2

Answers


  1. Your code concatenates your values:

    $op .= trim($tmp[0],"'"")." ";
    

    Try to replace this by just an assignment

    $op = trim($tmp[0],"'"")." ";
    

    Documentation

    Login or Signup to reply.
  2. $str = 'Ann is good,"Mike loves cooking"';
    $sentences = str_replace(["'", '"'], '', explode(',', $str));
    
    $names = array_map(fn($s) => ($words = explode(' ', trim($s))[0]), $sentences);
    
    print_r($names);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search