4

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.

4 Answers 4

6

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);
Sign up to request clarification or add additional context in comments.

3 Comments

The second solution is better :)
Can you please help. For the same code, If the result needed is as $test = 'aa,bb,cc,dd,ee' and other string as $match='cc'. I want the result as $match='' i.e if it matches the string then the $match variable can be made empty or can be skipped
Meh, I think he just wants $match = ''; inside the if condition. (on the second solution, I mean)
3

Try with preg_replace

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

$match ='cc';

echo $new = preg_replace('/'.$match.',|,'.$match.'$/', '', $test);

Output

aa,bb,dd,ee

2 Comments

what if cc located at the end? aa,bb,dd,cc
^^ "/$match,|,$match$"?
0
 $test = 'aa,bb,cc,dd,ee';
 $match='cc';
echo trim(str_replace(',,', ',' , str_replace($match,'',$test)),',');

DEMO

1 Comment

$match='aa' will give you ,bb,cc,dd,ee' - look at my answer - there is trim method involved.
0

Try this:

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

$temp = explode(',', $test);    
unset($temp[ array_search($match, $temp) ] );
$result = implode(',', $temp);

echo $result;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.