strcspn()函数是PHP中的内置函数,它在找到要搜索的指定字符的任何部分之前,返回字符串中存在的字符数。此函数区分大小写。
用法:
strcspn( $string, $charlist, $start, $length)
参数:此函数接受上面语法中所示的四个参数。前两个参数是必需的,必须提供,而其余两个参数是可选的。所有这些参数如下所述:
- $string :此必需参数指定要搜索的字符串
- $charlist :此必需参数指定在给定的$string中要搜索的字符列表。
- $start : 此可选参数指定从中开始搜索字符串的索引。
- 如果给定$start且它为非负数,则strcspn()将开始从该位置检查$string。
- 如果给出了$start并且为负,则strcspn()将开始从$string的末尾开始从该位置检查$string。
- $length :它指定需要搜索的$string字符数。其默认值是直到$string的末尾。
- 如果给出了$length且非负数,则将从起始位置开始检查$string中的$length个字符。
- 如果给出了$length且为负数,则将从起始位置开始检查$string,直到从$string的末尾开始检查$length个字符。
返回值:返回在字符串中找到$charlist参数中的任何字符之前,字符串中起始位置(包括空格)的字符数。
例子:
Input : $string = "Geeks for Geeks", $charlist = "mnopqr" Output : 7 Input : $string = "Geeks for Geeks", $charlist = "for" Output : 6
下面的程序将说明strcspn()函数的用法:
程序1:该程序显示了strcspn()函数的简单用法。
<?php
// Output is 6 because the input string
// contains 6 characters "Geeks " before
// the first character 'f' from the list
// "for" is found in the string.
echo strcspn("Geeks for Geeks", "for");
?>
输出:
6
程序2:该程序显示strcspn()函数的区分大小写。
<?php
// Output is 7 because the input string
// does not contain 'F' as specified in the list "For".
// Hence the first character from the
// list that is present in the string is 'o'
echo strcspn("Geeks for Geeks", "For");
?>
输出:
7
程序3:该程序显示了带有$start参数的strcspn()函数的使用。
<?php
// Searches from index 5 till
// the end of the string
echo strcspn("Geeks for Geeks", "G", 5);
?>
输出:
5
程序4:该程序说明了带有$length负参数的strspn()函数的用法。
<?php
// Searches from index 5 till 5-th position
// from end. Output is 0 since the character
// at $start (i.e. 5) is present in the
// specified list of characters
echo strcspn("Geeks for Geeks", " for", 5, -5);
?>
输出:
0
程序5:该程序显示了带有负$start参数的strcspn()函数的使用。
<?php
// Searches from 5th index from the end of the string
// Output is 0 as the character 'G' in the
// specified starting index is present in the
// given list of characters to be checked.
echo strcspn("Geeks for Geeks", "Geek", -5);
?>
输出:
0
参考:
http://php.net/manual/en/function.strcspn.php
相关用法
- PHP next()用法及代码示例
- PHP each()用法及代码示例
- d3.js d3.map.has()用法及代码示例
- p5.js day()用法及代码示例
- CSS var()用法及代码示例
- p5.js pow()用法及代码示例
- p5.js sq()用法及代码示例
- d3.js d3.map.set()用法及代码示例
- PHP pow( )用法及代码示例
- PHP pi( )用法及代码示例
- p5.js hex()用法及代码示例
- PHP Ds\Map get()用法及代码示例
注:本文由纯净天空筛选整理自RICHIK BHATTACHARJEE大神的英文原创作品 PHP | strcspn() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。