user930026
user930026

Reputation: 1657

php match a string from other string

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

Answers (4)

rgin
rgin

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

Arun Kumar M
Arun Kumar M

Reputation: 848

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

DEMO

Upvotes: 0

Bora
Bora

Reputation: 10717

Try with preg_replace

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

$match ='cc';

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

Output

aa,bb,dd,ee

Upvotes: 3

hsz
hsz

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

Related Questions