-
start
-
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.
If start is negative, the returned string will start at the start 'th character from the end of string .
length
-
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 ). If string is less than or equal to start characters long, FALSE will be returned.
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 a position beyond this truncation, an empty string will be returned.
下面,我详细总结一下关于substr的相关用法:
-
原型:
string
substr (
string $string ,
int $start [,
int $length ] ),它可以用于在一个较长的字符串中查找匹配的字符串或字符。$string为所要处理的字符串,$start为开始选取的位置,$length为要选取的长度
例:
- <?php
- $rest1 = substr("abcdef", 0, 0); // returns ""
- $rest2 = substr("abcdef", 0, 2); // returns "ab"
- $rest3 = substr("abcdef", 0, -1); // returns "abcde"
- $rest4 = substr("abcdef", 2,0); // returns ""
- $rest5 = substr("abcdef", 2,2); // returns "cd"
- $rest6 = substr("abcdef", 2, -1); // returns "cde"
- $rest7 = substr("abcdef", -2,0); // returns ""
- $rest8 = substr("abcdef", -2,2); // returns "ef"
- $rest9 = substr("abcdef", -2,-1); // returns "e"
- ?>
-
该函数在使用中有时也省略 $length,这个时候如果只用一个正数作为子字符串起点,将得到从起点到字符串结束的整个字符串。如果只用一个负数作为子字符串起点,将得到一个原字符串尾部的一个子字符串,字符个数等于负数的绝对值,其实原理和上述不省略$length时一样。只是不用再去判断所取字符的个数,单去判断起始位置就OK。
例:
-
- <?php
- $rest1 = substr("abcdef", 2); // returns "cdef"
- $rest2 = substr("abcdef", -2); // returns "ef"
- ?>
PHP中关于substr的用法详解
php.net中关于substr的说明很简单: