Home  >  Article  >  Backend Development  >  PHP removes the last character of a string and uses substr()_PHP tutorial

PHP removes the last character of a string and uses substr()_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:31:24673browse

Used in today's project, remove the last character in the string
The original string is 1,2,3,4,5,6,
Remove the last character ",", the final result is 1,2, 3,4,5,6
The code is as follows:

Copy code The code is as follows:

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


Interpretation:
Use PHP’s substr() method,
Syntax: string substr(string string, int start, int [length]);
Parameter 1: Original String;
Parameter 2: starting position of cutting;
Parameter 3: intercepted length;

Use like this:
$newstr = substr($str,0,strlen ($str)-1);
Truncate from the beginning to the penultimate digit, thus removing the last ",".


The system’s own functions can also achieve this effect, two methods:
1) substr($str, 0, -1)
2) rtrim($str, ",")

substr
Get part of the string.
Syntax: string substr(string string, int start, int [length]);
Return value: string
Function type: Data processing
Content description
This function converts a string into a string Take out length characters from the string starting from the start position. If start is a negative number, it starts from the end of the string. If the omitted parameter length exists but is a negative number, it means that the length character from the bottom is obtained.
Usage example
Copy code The code is as follows:

echo substr("abcdef", 1, 3); // Return "bcd"
echo substr("abcdef", -2); // Return "ef"
echo substr("abcdef", -3, 1); // Return "d"
echo substr("abcdef", 1, -1); // return "bcde"
?>


PHP rtrim() Function

Definition and Usage
rtrim() function removes whitespace characters or other predefined characters from the end of a string. Same as chop() function.

Grammar
参数 描述
string 必需。规定要转换的字符串。
charlist

可选。规定从字符串中删除哪些字符。

如果未设置该参数,则全部删除以下字符:

  • "
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