PHP学习之字符串比较和查找

2019-04-09 09:00:00王振洲

strtok标记时,用strtok($str, $token)来初始化,用strtok($token)来继续取值。
代码如下:

$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'
$str2 = strtok($str, ','); // 1
$str3 = strtok(','); // 2
$str4 = strtok(','); // 3
// array(86, 10, 88888888, 'Beijin')
$arr3 = sscanf('+86(10)88888888 Beijin', '+%d(%d)%d %s');

4.字符串查找
在PHP中,字符串的查找有三个系列。返回位置的、返回字符串的、掩码个数匹配。其中,返回位置的的函数一共有两个,strpos()和 strrpos();返回字符串的也有两个strstr()和strchr();返回掩码匹配数的函数有strspn()和strcspn()。
strpos表示从左边开始计数,返回要查找的字符串第一次出现的位置;strrpos表示从右边计数,返回要查找的字符串第一次出现的位置。
strstr表示从左边计数,返回要查找字符串第一次到结尾的子串(包括查找字符串),当查找的是字符时,可以用ascii码数字来表示字符;stristr表示不区分大小查找;strchr是strstr的别名;strrchr返回字符最后出现到结尾的子串。
strspn表示从左边计数,第一次出现非掩码之前的子串的字符数;strcspn表示从左边计数,第一次出现掩码之前的子串的字符数。
示例代码:

$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

参考资料: PHP程序设计,2003,第四章 字符串,字符串比较;字符串查找和处理
相关文章 大家在看