PHPРow从行中删除单个值?

时间:2012-12-01 09:21:08

标签: php row

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

我们需要找到 $ id 的值并删除 $ test2 test2 $ ,具体取决于位置 test2 在字符串中;

使用以下方式进行搜索:

$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$
}

如何删除单个值?

2 个答案:

答案 0 :(得分:2)

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

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

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

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

var_dump($result);

阅读更多:

答案 1 :(得分: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;