问题
I am using a loop to get values from my database and my result is like:
'name', 'name2', 'name3',
And I want it like this:
'name', 'name2', 'name3'
I want to remove the comma after the last value of the loop.
回答1:
Use the rtrim function:
rtrim($my_string, ',');
The Second parameter indicates the character to be deleted.
回答2:
Try:
$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');
回答3:
Try the below code:
$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);
Use this code to remove the last character of the string.
回答4:
You can use substr
function to remove this.
$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);
回答5:
rtrim
function
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
回答6:
At first I tried without a space rtrim($arraynama,",");
and got an invalid result.
Then I added a space and got a valid result:
$newarraynama=rtrim($arraynama,", ");
回答7:
use rtrim()
rtrim($string,',');
回答8:
It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this ini_set("mbstring.func_overload", 2);
$string = "'test1', 'test2', 'test3',";
echo mb_substr($string, 0, -1);
回答9:
its as simple as:
$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');
回答10:
It is better to use implode for that purpose. Implode is easy and awesome:
$array = ['name1', 'name2', 'name3'];
$str = implode(', ', $array);
Output:
name1, name2, name3
回答11:
You can use one of the following technique to remove the last comma(,)
Solution1:
$string = "'name', 'name2', 'name3',"; // this is the full string or text.
$string = chop($string,","); // remove the last character (,) and store the updated value in $string variable.
echo $string; // to print update string.
Solution 2:
$string = '10,20,30,'; // this is the full string or text.
$string = rtrim($string,',');
echo $string; // to print update string.
Solution 3:
$string = "'name', 'name2', 'name3',"; // this is the full string or text.
$string = substr($string , 0, -1);
echo $string;
来源:https://stackoverflow.com/questions/15408691/how-do-i-remove-the-last-comma-from-a-string-using-php