【函数功能】
该函数从符串截取指定部分。
【函数语法】
substr ($string, $start, $length = null)
【参数说明】
$string:必需,要返回其中一部分的字符串。
$start:必需,在字符串的何处开始,有以下几种情况:
正数:字符串从左到右第$start位置开始。
负数:字符串从右到左第$start位置开始。
0:从左到右第一个处开始。
$length:可选,截取字符串的长度。默认是从$start直到字符串的结尾,有以下两种情况:
正数:从 start 位置开始截取的长度。
负数:从字符串$start开始截取,到字符串从右到左第$length个结束。
【演示程序】
<?php
/**
* substr ($string, $start, $length = null)
* **/
$string = "Hello i am PHP!";
echo substr($string, 5);//length采用默认
echo "<br>";
echo substr($string, -4);//length采用默认,start采用负数
echo "<br>";
echo substr($string, 0,5);//
echo "<br>";
echo substr($string, 0,-5);//
echo "<br>";
echo substr($string, -6,-5);//
?>
【输出结果】
i am PHP!
PHP!
Hello
Hello i am
m
【特别注意】
1.该函数截取中文会出现乱码,要用另一个函数截取中文,后面会讲到。
2.如果 start 参数是负数且 length 小于或等于 start,则 length 为 0:即当$start和$length都为负数时,$start是从距离右端$start个处开始截取,而$length是距离最右端$length个处结束,所以当$start、$length都为负数时$start一定要比$length小才能截取到字符串。
3.PHP 版本:4+。
4.更新日志:在 PHP 5.2.2 到 5.2.6 版本中,如果 start 参数表示负截断或者越界位置,则返回 FALSE,其他版本则从 start 位置开始获取字符串。
【原版定义】
/**
* Return part of a string
* @link http://www.php.net/manual/en/function.substr.php
* @param string string <p>
* The input string. Must be one character or longer.
* </p>
* @param start int <p>
* If start is non-negative, the returned string
* will start at the start'th position in
* string, counting from zero. For instance,
* in the string 'abcdef', the character at
* position 0 is 'a', the
* character at position 2 is
* 'c', and so forth.
* </p>
* <p>
* If start is negative, the returned string
* will start at the start'th character
* from the end of string.
* </p>
* <p>
* If string is less than or equal to
* start characters long, false will be returned.
* </p>
* <p>
* Using a negative start
* ]]>
* </p>
* @param length int[optional] <p>
* If length is given and is positive, the string
* returned will contain at most length characters
* beginning from start (depending on the length of
* string).
* </p>
* <p>
* If length is given and is negative, then that many
* characters will be omitted from the end of string
* (after the start position has been calculated when a
* start is negative). If
* start denotes the position of this truncation or
* beyond, false will be returned.
* </p>
* <p>
* If length is given and is 0,
* false or &null; an empty string will be returned.
* </p>
* <p>
* If length is omitted, the substring starting from
* start until the end of the string will be
* returned.
* </p>
* Using a negative length
* ]]>
* @return string the extracted part of string; or false on failure, or
* an empty string.
*/
转载请注明出处:php1234.cn ,原文地址:http://www.php1234.cn/a/functions/2016/0927/78.html