Home  >  Article  >  Backend Development  >  How to remove characters at the end of string in php

How to remove characters at the end of string in php

青灯夜游
青灯夜游Original
2021-03-18 18:03:172671browse

php method to remove the characters at the end of the string: 1. Directly use the substr() function to trim the last character in reverse order, the syntax is "substr(string,0,-1)"; 2. Use rtrim() Function, syntax "rtrim(string,charlist)".

How to remove characters at the end of string in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php removes strings The last character

Method 1: Use the substr() function

Use the substr() function directly to cut off the last character in reverse order

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$str = &#39;123,234,345,&#39;;
echo "原字符串:",$str,&#39;<br/>&#39;;
echo "去掉末尾字符的字符串:",substr($str,0,-1);
?>

Output:

原字符串:123,234,345,
去掉末尾字符的字符串:123,234,345

Description:

substr() function returns a part of a string. Syntax:

substr(string,start,length)

How to remove characters at the end of string in php

Method 2: Use the rtrim() function

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

1. Specify the last character

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$str = &#39;123,234,345,&#39;;
echo "原字符串:",$str,&#39;<br/>&#39;;
echo "去掉末尾字符的字符串:",rtrim($str,&#39;,&#39;);
?>

Output:

原字符串:123,234,345,
去掉末尾字符的字符串:123,234,345

2. Don’t know the last character

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$str = &#39;123,234,345,1&#39;;
echo "原字符串:",$str,&#39;<br/>&#39;;

//不知道末尾字符,需先获取末字符
$last_char=$str{strlen($str)-1}; 
echo "去掉末尾字符的字符串:",rtrim($str,$last_char);
?>

Output:

原字符串:123,234,345,1
去掉末尾字符的字符串:123,234,345,

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove characters at the end of 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