Home  >  Article  >  Backend Development  >  How to remove the last character from a php string?

How to remove the last character from a php string?

青灯夜游
青灯夜游Original
2020-07-17 14:44:202971browse

In PHP, you can use the substr() function to remove the last character; the syntax is "substr(original string, length of string -1)", where you can use the strlen() function to calculate characters The length of the string.

How to remove the last character from a php string?

#substr() function returns a portion of a string.

Note: If the start parameter is negative and length is less than or equal to start, length is 0. [Related recommendations: PHP Tutorial]

Syntax:

string substr(string string, int start, int [length]);
  • Parameter 1: Original string;

  • Parameter 2: starting position of cutting;

  • Parameter 3: intercepted length;

php Method to remove the last character from a string:

substr($str,0,strlen($str)-1);

Intercept from the beginning to the penultimate character, thus removing the last character.

Example:

$str = "1,2,3,4,5,6,";
$newstr = substr($str,0,strlen($str)-1);
echo $newstr;

Output:

1,2,3,4,5,6

Expand knowledge:

rtrim() function from Whitespace characters or other predefined characters are removed starting from the end of the string. Same as chop() function.

Grammar

rtrim(string,charlist)

How to remove the last character from a php string?

Usage example

$str = "1,2,3,4,5,6,";
$newstr = rtrim($str, ",");
echo $newstr;

Output:

1,2,3,4,5,6

Related learning recommendations:PHP programming from entry to proficiency

The above is the detailed content of How to remove the last character from a php string?. 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