Php matches a line from another line

I have a line like $test = 'aa,bb,cc,dd,ee' and another line like $match='cc' . I want the result to be $result='aa,bb,dd,ee' . I can’t get the result at will, because I’m not sure which PHP function can give the desired result.

Also, if I have a line like $test = 'aa,bb,cc,dd,ee' and another line like $match='cc' . I want the result to be $match='' . If $ match is found in $ test , then the value of $ match may be skipped

Any help would be really appreciated.

+4
source share
4 answers

You can try:

 $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); 
+6
source

Try with preg_replace

 $test = 'aa,bb,cc,dd,ee'; $match ='cc'; echo $new = preg_replace('/'.$match.',|,'.$match.'$/', '', $test); 

Exit

 aa,bb,dd,ee 
+3
source
  $test = 'aa,bb,cc,dd,ee'; $match='cc'; echo trim(str_replace(',,', ',' , str_replace($match,'',$test)),','); 

Demo

0
source

Try the following:

 $test = 'aa,bb,cc,dd,ee'; $match = 'cc'; $temp = explode(',', $test); unset($temp[ array_search($match, $temp) ] ); $result = implode(',', $temp); echo $result; 
0
source

Source: https://habr.com/ru/post/1499309/


All Articles