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

How to remove the last character from a php string?

青灯夜游
Release: 2023-03-02 16:38:01
Original
3027 people have browsed it

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]);
Copy after login
  • 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);
Copy after login

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;
Copy after login

Output:

1,2,3,4,5,6
Copy after login
Copy after login

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)
Copy after login

How to remove the last character from a php string?

Usage example

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

Output:

1,2,3,4,5,6
Copy after login
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template