how do i remove a comma off the end of a string?

后端 未结 10 1477
难免孤独
难免孤独 2020-11-27 14:15

I want to remove the comma off the end of a string. As it is now i am using

$string = substr($string,0,-1);

but that only removes the last

相关标签:
10条回答
  • 2020-11-27 14:46

    A simple regular expression would work

    $string = preg_replace("/,$/", "", $string)
    
    0 讨论(0)
  • 2020-11-27 14:48

    Precede that with:

    if(substr($string, -1)==",")
    
    0 讨论(0)
  • 2020-11-27 14:50
    $string = rtrim($string, ',');
    

    Docs for rtrim here

    0 讨论(0)
  • 2020-11-27 14:53

    i guess you're concatenating something in the loop, like

    foreach($a as $b)
      $string .= $b . ',';
    

    much better is to collect items in an array and then join it with a delimiter you need

    foreach($a as $b)
      $result[] = $b;
    
    $result = implode(',', $result);
    

    this solves trailing and double delimiter problems that usually occur with concatenation

    0 讨论(0)
提交回复
热议问题