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

How to remove characters at the end of string in php

青灯夜游
Release: 2023-03-08 20:20:02
Original
2745 people have browsed it

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

Output:

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

Description:

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

substr(string,start,length)
Copy after login

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

Output:

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

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

Output:

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

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!

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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template