php match a string from other string

arrays, php, string

Solution

You can try with:

$test   = 'aa,bb,cc,dd,ee';
$match  = 'cc';

$output = trim(str_replace(',,', ',', str_replace($match, '', $test), ','));

or:

$testArr = explode(',', $test);
if(($key = array_search($match, $testArr)) !== false) {
  unset($testArr[$key]);
}
$output  = implode(',', $testArr);

Problem

I have a string as `$test = 'aa,bb,cc,dd,ee'` and other string as `$match='cc'`. I want the result as `$result='aa,bb,dd,ee'`. I am not able to get te result as desired as not sure which PHP function can give the desired output. Also if I have a string as `$test = 'aa,bb,cc,dd,ee'` and other string as `$match='cc'`. I want the result as `$match=''`. i.e if $match is found in $test then $match value can be skipped Any help will be really appreciated.

Original source