Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php match a string from other string

Tags:

arrays

string

php

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.

like image 498
user930026 Avatar asked Jan 13 '23 12:01

user930026


2 Answers

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);
like image 181
hsz Avatar answered Jan 21 '23 21:01

hsz


Try with preg_replace

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

$match ='cc';

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

Output

aa,bb,dd,ee
like image 33
Bora Avatar answered Jan 21 '23 19:01

Bora