PHP的substr()函数如何解析?代码实例解析详述。

更新于
2026-09-27 17:02:49
1阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计561个文字,预计阅读时间需要3分钟。

PHP的substr()函数如何解析?代码实例解析详述。

在PHP的实战中,我们经常需要解析URL字符串,截取所需片段。PHP为我们提供了substr()函数,可以轻松获取所需数据。简单来看,Psubstr()函数能帮我们快速定位到目标数据。

在PHP的实战中,我们经常需要对URL字符串进行解析,截取我们所需要的片段,PHP为我们提供了substr()函数,我们可很轻松的获取我们所需要的数据,本文就带大家一起来看一看PHP中的substr()函数。

首先我们先看一看看substr()函数的语法:

substr ( string $string , int $start , int $length = ? )

  • $string:需要截取的原字符串

  • $start:需要开始的索引位置(值可以为正整数、负整数、0)

  • $length:需要筛选的长度(值可以为正整数、负整数、0)若为空则默认截取至结束

  • 返回值:经过截取得到的新字符串,若错误则返回false。

代码实例:

1.若参数都为非负整数

<?php echo substr('php.cn is all right', 1); echo "<br>"; echo substr('php.cn is all right', 1, 3); echo "<br>"; echo substr('php.cn is all right', 0, 4); echo "<br>"; echo substr('php.cn is all right', 0, 8); ?>

输出: hp.cn is all right hp. php. php.cn i

2.若$start出现负整数

PHP的substr()函数如何解析?代码实例解析详述。

<?php echo substr("php.cn is all right", -1); echo "<br>"; echo substr("php.cn is all right", -2); echo "<br>"; echo substr("php.cn is all right", -3, 1); ?>

输出: t ht g

3.若$length出现负整数

<?php echo substr("php.cn is all right", 0,-1); echo "<br>"; echo substr("php.cn is all right",2, -1); echo "<br>"; echo substr("php.cn is all right",4, 4); echo "<br>"; echo substr("php.cn is all right",-3, -1); ?>

输出:php.cn is all righ p.cn is all righ cn i gh

本文共计561个文字,预计阅读时间需要3分钟。

PHP的substr()函数如何解析?代码实例解析详述。

在PHP的实战中,我们经常需要解析URL字符串,截取所需片段。PHP为我们提供了substr()函数,可以轻松获取所需数据。简单来看,Psubstr()函数能帮我们快速定位到目标数据。

在PHP的实战中,我们经常需要对URL字符串进行解析,截取我们所需要的片段,PHP为我们提供了substr()函数,我们可很轻松的获取我们所需要的数据,本文就带大家一起来看一看PHP中的substr()函数。

首先我们先看一看看substr()函数的语法:

substr ( string $string , int $start , int $length = ? )

  • $string:需要截取的原字符串

  • $start:需要开始的索引位置(值可以为正整数、负整数、0)

  • $length:需要筛选的长度(值可以为正整数、负整数、0)若为空则默认截取至结束

  • 返回值:经过截取得到的新字符串,若错误则返回false。

代码实例:

1.若参数都为非负整数

<?php echo substr('php.cn is all right', 1); echo "<br>"; echo substr('php.cn is all right', 1, 3); echo "<br>"; echo substr('php.cn is all right', 0, 4); echo "<br>"; echo substr('php.cn is all right', 0, 8); ?>

输出: hp.cn is all right hp. php. php.cn i

2.若$start出现负整数

PHP的substr()函数如何解析?代码实例解析详述。

<?php echo substr("php.cn is all right", -1); echo "<br>"; echo substr("php.cn is all right", -2); echo "<br>"; echo substr("php.cn is all right", -3, 1); ?>

输出: t ht g

3.若$length出现负整数

<?php echo substr("php.cn is all right", 0,-1); echo "<br>"; echo substr("php.cn is all right",2, -1); echo "<br>"; echo substr("php.cn is all right",4, 4); echo "<br>"; echo substr("php.cn is all right",-3, -1); ?>

输出:php.cn is all righ p.cn is all righ cn i gh