简体   繁体   中英

PHP Рow to remove a single value from row?

code:

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

We need to find the value of $id and remove $test2 or test2$ depending on the position test2 in the string ;

To search using:

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

how to remove a single value?

You explode() the string, remove the elements, and implode() it back together:

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

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

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

var_dump($result);

Read More:

You need to replace the first occurence of the '$test2' if exists, if not, replace the first occurence of '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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM