Home  >  Article  >  Backend Development  >  谈谈PHP中substr和substring的正确用法及相关参数的介绍_php实例

谈谈PHP中substr和substring的正确用法及相关参数的介绍_php实例

WBOY
WBOYOriginal
2016-06-07 17:10:321031browse

大家都知道js中字符串截取字符有函数substr和substring,那php呢,php没有直接可用的substring函数,但是有substr函数。
不信自己可以测试一下。 下面给出一段正确的代码。

<&#63;
$a="me";
echo(substr($a,,));//输出me
&#63;>
下面又给出一段错误的代码
<&#63;
$a="me";
echo(subString($a,,));
&#63;>

substr() 函数返回字符串的一部分。

substr(string,start,length)

string:要截取的字符串

start:

正数 - 在字符串的指定位置开始
负数 - 在从字符串结尾的指定位置开始
0 - 在字符串中的第一个字符处开始

length:

可选。规定要返回的字符串长度。默认是直到字符串的结尾。
正数 - 从 start 参数所在的位置返回
负数 - 从字符串末端返回

PHP substr()的用法详解

定义和用法

substr() 函数返回字符串的一部分。使用substr()函数截取中文可能会出现乱码,建议使用mb_substr() 函数截取中文。

语法

substr(string,start,length)

参数 描述
string 必需。规定要返回其中一部分的字符串。
start

必需。规定在字符串的何处开始。

  • 正数 - 在字符串的指定位置开始
  • 负数 - 在从字符串结尾的指定位置开始
  • 0 - 在字符串中的第一个字符处开始
length

可选。规定要返回的字符串长度。默认是直到字符串的结尾。

  • 正数 - 从 start 参数所在的位置返回
  • 负数 - 从字符串末端返回

提示和注释

注释:如果 start 是负数且 length 小于等于 start,则 length 为 0。

例子

<&#63;php
$str = 'hello world!';
echo substr($str, 4); // o world! 左起第4开始向右截取到末尾
echo substr($str, 4, 5); // o wor 左起第4开始向右取5位
echo substr($str, 4, -1); // o world 左起第4与右起第1之间的字符
echo substr($str, -8, 4); // o wo 右起第8开始向右截取4位
echo substr($str, -8,-2); // o worl 右起第8与右起第2之间的字符
&#63;>
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