php匹配其他字符串中的字符串

时间:2013-08-28 06:55:53

标签: php arrays string

我的字符串为$test = 'aa,bb,cc,dd,ee',其他字符串为$match='cc'。我希望结果为$result='aa,bb,dd,ee'。 我无法获得所需的结果,因为不确定哪个PHP函数可以提供所需的输出。

此外,如果我的字符串为$test = 'aa,bb,cc,dd,ee',其他字符串为$match='cc'。我希望结果为$match=''。即如果在 $ test 中找到 $ match ,则可以跳过 $ match

任何帮助都将非常感激。

4 个答案:

答案 0 :(得分:6)

您可以尝试:

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

$output = trim(str_replace(',,', ',', str_replace($match, '', $test), ','));

或:

$testArr = explode(',', $test);
if(($key = array_search($match, $testArr)) !== false) {
  unset($testArr[$key]);
}
$output  = implode(',', $testArr);

答案 1 :(得分:3)

尝试使用preg_replace

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

$match ='cc';

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

输出

aa,bb,dd,ee

答案 2 :(得分:0)

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

DEMO

答案 3 :(得分:0)

试试这个:

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

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

echo $result;