PHP | strspn()函数

strspn()函数是PHP中的一个内置函数,用于查找字符串初始段的长度,该字符串完全由作为参数传递给函数的给定字符列表中包含的字符组成。

null

语法:

strspn( $string, $charlist, $start, $length)

参数: 此函数接受上述语法中所示的四个参数。前两个参数是必需的,必须提供,而其余两个参数是可选的。所有这些参数如下所述:

  • $string: 此必填参数指定要搜索的字符串。
  • $charlist: 此必填参数指定要在给定的$字符串中搜索的字符列表。
  • $start: 此可选参数指定要从中开始搜索字符串的索引。
    • 如果 $start 如果给定且为非负,则strspn()将开始检查 $string 从那个位置。
    • 如果 $start 如果给定且为负值,则strspn()将从$string末尾的该位置开始检查$string。
  • $length: 它指定需要搜索的$string的字符数。它的默认值是直到$string结束。
    • 如果 $length 如果给定且为非负,则将从起始位置检查$string中的$length字符。
    • 如果 $length 如果给定且为负数,则将从起始位置检查$string,直到从$string结尾检查$length字符。

返回值: 此函数返回在仅包含charlist参数中的字符的字符串中找到的字符数。

例如:

Input : $string = "abcdefghijk", $charlist = "abcjkl"
Output : 3

Input : $string = "Geeks for Geeks", $charlist = "Geeksfor "
Output : 15

下面的程序演示了strspn()函数:

项目1:

<?php
// Output is 15 because whole input string
// contains all characters from given char list
// "Geeksfor "
echo strspn ( "Geeks for Geeks" , "Geeksfor " );
?>


输出:

15

项目2: 这个程序演示了strspn()函数的大小写敏感性。

<?php
// Output is 0 because there is no substring
// which contains all characters of given char
// list.
echo strspn ( "Geeks for Geeks" , "geeks" );
?>


输出:

0

方案3: 这个程序演示了使用带有$start和$length参数的strspn()函数。

<?php
// Searches substring starting from index 5
// and length 9 with all characters in char
// list " for"
echo strspn ( "Geeks for Geeks" , " for" , 5, 9);
?>


输出:

5

方案4: 这个程序演示了带负$length参数的strspn()函数的用法。

<?php
// Searches from index 5 till 5-th position from
// end.
echo strspn ( "Geeks for Geeks" , " for" , 5, -5);
?>


输出:

5

方案5: 这个程序演示了带负$start参数的strspn()函数的用法。

<?php
// Searches from 5-th index from end
echo strspn ( "Geeks for Geeks" , "for" , -5);
?>


输出:

0

参考: http://php.net/manual/en/function.strspn.php

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享