0

代码:

$str = 'test2$test2$test3$test3$test4';
$id = 'test2';

我们需要找到$id的值并根据字符串中的位置test2删除$test2test2$ ;

要使用搜索:

$substr_count1 = substr_count ($str, '$test2');
$substr_count2 = substr_count ($str, 'test2$');
if ($substr_count1> 0) {
//if exist $test2 then need delete single value $test2 from row and row will be
// $str = 'test2$test3$test3$test4'
// find the value of $test2
// how to remote one value $test2
}
elseif ($substr_count2> 0) {
//if exist test2$ then need delete single value test2$ from row and row will be
// $str = 'test2$test3$test3$test4'
// find the value of test2$
// how to remote one value test2$
}

如何删除单个值?

4

2 回答 2

2

explode()将字符串删除,然后implode()将其重新组合在一起:

$str = 'test2$test2$test3$test3$test4';
$id = 'test2';

$array = explode('$', $str);

$result = implode('$', array_diff($array, array($id)));

var_dump($result);

阅读更多:

于 2012-12-01T09:36:38.210 回答
0

如果存在,则需要替换第一次出现的“$test2”,如果不存在,则替换第一次出现的“test$”:

$str = 'test2$test2$test3$test3$test4';
$id = 'test2';

$position1=strpos($str,'$'.$id);
$position2=strpos($str,$id.'$');

//if the first occurence is the '$test2':
if($position1<$position2)
{
$str= preg_replace('/'.'\$'.$id.'/', '', $str, 1);
}
//If the first occurence is the 'test$'
else
{
$str= preg_replace('/'.$id.'\$'.'/', '', $str, 1);
}

echo $str;
于 2012-12-01T09:34:10.007 回答