當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP strcspn()用法及代碼示例

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



相關用法


注:本文由純淨天空篩選整理自RICHIK BHATTACHARJEE大神的英文原創作品 PHP | strcspn() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。