Search code examples
phparraysregexexplodearray-difference

How to remove given item from comma separated list?


$list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';

Is there a regex or a function that will work as follows?

1)"Tue"       return string ->"Mon,Wed,Thrs,Fri,Sat,Sun"
2)"Thrs, Mon"     return string ->"Tue,Wed,Fri,Sat,Sun"
3)"Sun,Wed,Fri"       return string ->"Mon,Tue,Thrs,Sat"
4)"Fri"     return string ->"Mon,Tue,Wed,Thrs,Sat,Sun"

Below works fine for removing just one item from the string. What if I want to remove more than one item like above?

$input = 'Wed';
$list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';
    $array1 = Array($input);
    $array2 = explode(',', $list);
    $array3 = array_diff($array2, $array1);

    $output = implode(',', $array3);

    echo $output;

Solution

  • Use explode on the $input variable as well:

    $input = 'Wed';
    $list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';
    $array1 = explode(',', $input);
    $array2 = explode(',', $list);
    $array3 = array_diff($array2, $array1);
    
    $output = implode(',', $array3);
    
    echo $output;