Home  >  Article  >  Backend Development  >  How to remove first and last characters in PHP

How to remove first and last characters in PHP

藏色散人
藏色散人Original
2021-02-28 11:24:172563browse

PHP去掉头尾字符的方法:首先创建一个PHP示例文件;然后定义一个头尾含有特殊字符的字符串;最后通过trim函数去除首尾空格或者tab等字符。

How to remove first and last characters in PHP

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑

可用trim去除首尾空格及如下字符:

"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - 纵向列表符
"\r" - 回车

为了便于展示,我在打印输出时首尾分别加了"start"与"end"来观察是否存在空格。

How to remove first and last characters in PHP

字符串首尾两端的空格都被去除了。

How to remove first and last characters in PHP

如果只需去除首部空格可用ltrim,如果只需去除尾部空格可用rtrim。【推荐学习:《PHP视频教程》】

How to remove first and last characters in PHP

trim,ltrim与rtrim的结果分别如下。

How to remove first and last characters in PHP

trim函数还有第二个参数,如果设置了,表示是去除该参数中指定的字符,如下面设置为". ",表示去除"."与" "。

How to remove first and last characters in PHP

可以看到首部空格,尾部"."与空格均被去除了。

How to remove first and last characters in PHP

The above is the detailed content of How to remove first and last characters 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