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

后端 未结 10 1476
难免孤独
难免孤独 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:26

    If you're concatenating something in the loop, you can do it in this way too:

    $coma = "";
    foreach($a as $b){
        $string .= $coma.$b;
        $coma = ",";
    }
    
    0 讨论(0)
  • 2020-11-27 14:27

    I had a pesky "invisible" space at the end of my string and had to do this

     $update_sql=rtrim(trim($update_sql),',');
    

    But a solution above is better

     $update_sql=rtrim($update_sql,', ');
    
    0 讨论(0)
  • 2020-11-27 14:40

    rtrim ($string , ","); is the easiest way.

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

    have a look at the rtrim function

    rtrim ($string , ",");
    

    the above line will remove a char if the last char is a comma

    0 讨论(0)
  • 2020-11-27 14:44
    if(substr($str, -1, 1) == ',') {
    
      $str = substr($str, 0, -1);
    
    }
    

    http://php.net/manual/en/function.substr.php

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

    This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:

    if (substr($string, -1, 1) == ',')
    {
      $string = substr($string, 0, -1);
    }
    

    If you want to remove all commas from the end of a line use the simpler:

    $string = rtrim($string, ',');
    

    The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:

    $string = rtrim($string, ", \t\n");
    
    0 讨论(0)
提交回复
热议问题