3.分解字符串 在PHP中,字符串的分解用explode,合并用implode(join是implode的别名),还有另一个函数slipt也可以分解(正则分解),但5.3以后版本已经不推介了, 另外PHP中还有一个sscanf()函数,用于读取字符串。 strtok标记时,用strtok($str, $token)来初始化,用strtok($token)来继续取值,代码如下: 1 2 3 4 5 | $str = '1,2,3' ;
$arr1 = explode ( ',' , $str ); // array('1', '2', '3')
$arr2 = explode ( ',' , $str , 2); // array('1', '2,3')
$str1 = implode( ',' , $arr1 ); // '1,2,3'
$arr3 = sscanf( '+86(10)88888888 Beijin' , '+%d(%d)%d %s' );
|
4.字符串查找 在PHP中,字符串的查找有三个系列,返回位置的、返回字符串的、掩码个数匹配,其中,返回位置的的函数一共有两个,strpos()和strrpos();返回字符串的也有两个strstr()和strchr()。 strpos表示从左边开始计数,返回要查找的字符串第一次出现的位置;strrpos表示从右边计数,返回要查找的字符串第一次出现的位置。 strstr表示从左边计数,返回要查找字符串第一次到结尾的子串(包括查找字符串),当查找的是字符时,可以用ascii码数字来表示字符;stristr表示不区分大小查找;strchr是strstr的别名;strrchr返回字符最后出现到结尾的子串。 strspn表示从左边计数,第一次出现非掩码之前的子串的字符数;strcspn表示从左边计数,第一次出现掩码之前的子串的字符数。 示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 | $pos = strpos ( 'This a hello world program' , ' ' ); // 4
$pos = strpos ( 'This a hello world program' , 32); // 4
$pos = strrpos ( 'This a hello world program' , ' ' ); // 18
$pos = strrpos ( 'This a hello world program' , 32); // 18
$str = strstr ( 'This a hello world program' , ' ' ); // " a hello world program"
$str = strstr ( 'This a hello world program' , 32); // " a hello world program"
$str = stristr ( 'This a hello world program' , ' A' ); // "a hello world program"
$str = stristr ( 'This a hello world program' , 65); // "a hello world program"
$str = strrchr ( 'This a hello world program' , ' ' ); // " program"
$str = strrchr ( 'This a hello world program' , 32); // " program"
$str1 = "12345 12345 12345" ;
$len = strspn ( $str1 , '12345' ); // 5
$len = strcspn ( $str1 , ' ' ); //5
|
|