search
Homephp教程php手册php去掉字符串的最后一个字符附substr()的用法

今天项目中用到,去掉字符串中的最后一个字符
原字符串1,2,3,4,5,6,
去掉最后一个字符",",最终结果为1,2,3,4,5,6
代码如下:

复制代码 代码如下:


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



解读:
采用php的substr()方法,
语法: string substr(string string, int start, int [length]);
参数1:原字符串;
参数2:切割的起始位置;
参数3:截取的长度;

按这样来使用:
$newstr = substr($str,0,strlen($str)-1);
从开头截取,一直截取到倒数第二位,这样就把最后的","去掉了。


系统自带的函数也可实现这样的效果,两种方法:
1) substr($str, 0, -1)
2)rtrim($str, ",")

substr
取部份字符串。
语法: string substr(string string, int start, int [length]);
返回值: 字符串
函数种类: 资料处理
内容说明
本函数将字符串 string 的第 start 位起的字符串取出 length 个字符。若 start 为负数,则从字符串尾端算起。若可省略的参数 length 存在,但为负数,则表示取到倒数第 length 个字符。
使用范例

复制代码 代码如下:



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



PHP rtrim() 函数

定义和用法
rtrim() 函数从字符串的末端开始删除空白字符或其他预定义字符。同chop()函数。

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

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

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

  • "\0" - ASCII 0, NULL
  • "\t" - ASCII 9, 制表符
  • "\n" - ASCII 10, 新行
  • "\x0B" - ASCII 11, 垂直制表符
  • "\r" - ASCII 13, 回车
  • " " - ASCII 32, 空格

使用范例
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools