php中substr的用法详解

php中substr的用法详解

php.net中关于substr的说明很简单:
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
//此教程来源于97xxoo教程网([url=http://www.97xxoo.org]www.97xxoo.org[/url])
查看完整的教程请点:[url=http://www.97xxoo.org/article/1/2008/20081115345.shtml]http://www.97xxoo.org/article/1/2008/20081115345.shtml[/url]
$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"
?>
$start如果为非负数,在字符串中以0为开头从左向右开始记数,[url=http://www.caoliushequ8.cn]草榴社区[/url]即0代表字符"a",1则代表字符"b",以此类推。如果是负数,在字符串中以1为开头从右向左开始记数,即-1代表字符"f",-2代表字符"e",同理也可以此类推。
该函数在使用中有时也省略 $length,这个时候如果只用一个正数作为子字符串起点,将得到从起点到字符串结束的整个字符串。如果只用一个负数作为子字符串起点,将得到一个原字符串尾部的一个子字符串,字符个数等于负数的绝对值,其实原理和上述不省略$length时一样。只是不用再去判断所取字符的个数,单去判断起始位置就OK。
例:
<?php
$rest1 = substr("abcdef", 2); // returns "cdef"
$rest2 = substr("abcdef", -2); // returns "ef"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值