Reputation: 1657
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.
Upvotes: 4
Views: 102
Reputation: 2311
Try this:
$test = 'aa,bb,cc,dd,ee';
$match = 'cc';
$temp = explode(',', $test);
unset($temp[ array_search($match, $temp) ] );
$result = implode(',', $temp);
echo $result;
Upvotes: 0
Reputation: 848
$test = 'aa,bb,cc,dd,ee';
$match='cc';
echo trim(str_replace(',,', ',' , str_replace($match,'',$test)),',');
Upvotes: 0
Reputation: 10717
Try with preg_replace
$test = 'aa,bb,cc,dd,ee';
$match ='cc';
echo $new = preg_replace('/'.$match.',|,'.$match.'$/', '', $test);
aa,bb,dd,ee
Upvotes: 3
Reputation: 152216
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);
Upvotes: 6