Home  >  Article  >  Backend Development  >  How to remove the last comma from a string in php

How to remove the last comma from a string in php

藏色散人
藏色散人Original
2021-02-24 10:15:483289browse

php method to remove the last comma from a string: 1. Create a PHP sample file; 2. Define a string with a comma; 3. Through "rtrim($str, ',');" This method removes the last comma from the string. The rtrim() function is used to remove blank characters or other predefined characters on the right side of a string. The syntax is "rtrim(string,charlist)". The parameter "charlist" specifies the characters to be deleted from the string.

How to remove the last comma from a string in php

#The operating environment of this article: Windows 7 system, PHP8, Dell G3 computer.

The PHP character filter function removes the last comma from the string. It is easier to solve it with the rtrim function that comes with PHP.

First explain it separately,

trim过滤字符串两端,
rtrim过滤字符串尾部
ltrim过滤字符串首部.

You can only use str_replace to filter the keys in the string.

For example,

PHP code

The code is as follows:

$str = '123,333,234,';
echo rtrim($str, ',');

How to remove the last comma from a string in php

PHP rtrim

rtrim() function removes whitespace characters or other predefined characters on the right side of a string.

Syntax:

rtrim(string,charlist)
Parameters Description
string Required. Specifies the string to check.
charlist

Optional. Specifies which characters are removed from a string. If omitted, all the following characters are removed:

  • "\0" - NULL
  • "\t" - TAB
  • "\n" - Line feed
  • "\x0B" - vertical tab character
  • "\r" - carriage return
  • " " - space

Return value: Return the modified string.

Example: Remove spaces on the right side of the string

<?php
header("Content-type:text/html;charset=utf-8");
$str = "Hello World    ";
echo "不使用 rtrim:" . $str."!";
echo "<br>";
echo "使用 rtrim:" . rtrim($str)."!";
?>

How to remove the last comma from a string in php

[Recommended: PHP video tutorial]

The above is the detailed content of How to remove the last comma from a string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn