如何从字符串中删除特定数字,如果重复该数字,我只需要删除一次即可。
$string = "1 3 5 15 5";
//Remove 5
$valuetoremove = "5";
$newvalue = "1 3 15 5";
我尝试过 str_replace,但这会删除所有重复的数字。
str_replace("5"," ","1 3 5 15 5");
$newvalue = "1 3";
答案 0 :(得分:1)
如果您只想一次删除它,那么我想这就是您想要的
$string = "1 3 5 15 5";
$valueToRemove = "5";
$exploded = explode(" ", $string);
// $exploded = ["1", "3", "5", "15", "5"];
$key = array_search($valueToRemove, $exploded, true);
if ($key !== false) {
unset($exploded[$key]);
}
$newValue = implode(" ", $exploded);