PHP remove number from comma seperated string stored in db [duplicate]

左心房为你撑大大i 提交于 2020-05-24 06:21:11

问题


I am storing numbers in a database with a string like 5,55,15,17,2,35

I want to remove say number 5 from the string, keeping the comma seperation set like it is.

The problem with using str_replace() is that all of the 5's will be removed. If i use str_replace('5,'', $string) thats fine, but the comma wouldn't be after the 5 if it was in the middle of the string or at the end. That same str_replace would also remove part of 15, and 55,

Am i missing something?


回答1:


$array = explode(',', $string);
foreach ($array as $k => $v)
  if ($v == 5) unset($array[$k]);
$string = implode(',', $array);

You probably shouldn't be storing a comma separated list of values in a single database column in the first place. It looks like a one-to-many association, which should be modeled with a separate table.




回答2:


Split the string first by comma so you can work with the numbers directly. Remove 5 from the array, then recombine the array into a comma-delimited string.

Here's an example:

<?php
    $input = '5,55,15,17,2,35';
    echo "Input: $input<br />";

    // Split the string by "exploding" the string on the delimiter character
    $nums = explode(',', $input);

    // Remove items by comparing to an array containing unwanted elements
    $nums = array_diff($nums, array(5));

    // Combine the array back into a comma-delimited string
    $output = implode(',', $nums);

    echo "Output: $output<br />";

    // Outputs:
    // Input: 5,55,15,17,2,35
    // Output: 55,15,17,2,35

?>



回答3:


str_replace([$num.",",",".$num],"",$input);



回答4:


U can try something like this:

// Convert string into array of numbers
$arrOfNumbers = explode(',', $string);

// Find id of number for del
$numberForDelId = array_search($numberForDel, $arrOfNumbers);

//Delete number
unset($arrOfNumbers[$numberForDelId]);

// Convert back to string
$resultString = implode(',' $arrOfNumbers)



回答5:


You should:

  1. get the string
  2. then "explode" the values into an array
  3. and re-create the string without the number you want to remove.


来源:https://stackoverflow.com/questions/11937097/php-remove-number-from-comma-seperated-string-stored-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!