PHP字符串剪辑substr()的一些小技巧.
二月13
在PHP中要剪辑一段字符串有很多方法,最简单的就是substr()了
在手册里的用法为:
substr
Description
string substr ( string string, int start [, int length] )
substr() returns the portion of string specified by the start and length parameters.
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.
很简单substr(“字符串内容(可以是一个变量)”,开始,结束)
这里说一下开始是从0开始,也就是如果字符串是12345,开始写0结束写4那么就输出12345,如果从1开始就是2345.
这里一个技巧, 如果你要删除最后一个或几个字符怎么办呢? 比较”笨”的做法是算出这个字符串一共多少个字然后在用0到总字符数-1. 这里有更快更简单的方法.substr(‘12345a’,0,-1)这样输出的是12345,对了就是那么简单. -1等于总字符减去1. 同样的如果要删除后4个字符那么用0到-4就可以了.