PHP Conference Japan 2024

strcspn

(PHP 4, PHP 5, PHP 7, PHP 8)

strcspn尋找與遮罩不符的初始區段長度

說明

strcspn(
    字串 $string,
    字串 $characters,
    整數 $offset = 0,
    ?int $length = null
): int

傳回 string 字串起始區段的長度,該區段不包含任何 characters 字串中的字元。

如果省略 offsetlength,則會檢查整個 string。如果包含它們,則效果與呼叫 strcspn(substr($string, $offset, $length), $characters) 相同(有關更多資訊,請參閱 substr)。

參數

string

要檢查的字串。

characters

包含所有不允許字元的字串。

offset

開始搜尋 string 的位置。

如果給定 offset 且為非負數,則 strcspn() 將從 string 的第 offset 個位置開始檢查。例如,在字串 'abcdef' 中,位置 0 的字元是 'a',位置 2 的字元是 'c',依此類推。

如果給定 offset 且為負數,則 strcspn() 將從 string 末尾的第 offset 個位置開始檢查。

length

要檢查的 string 區段的長度。

如果給定 length 且為非負數,則將從起始位置開始檢查 stringlength 個字元。

如果給定 length 且為負數,則將從起始位置檢查 stringstring 末尾的 length 個字元。

返回值

傳回 string 字串起始區段的長度,該區段完全由不在 characters 中的字元組成。

注意事項:

設定 offset 參數時,傳回的長度是從這個位置開始計算,而不是從 string 的開頭開始計算。

更新日誌

版本 說明
8.4.0 在 PHP 8.4.0 之前,當 characters 為空字串時,搜尋會錯誤地在 string 的第一個空位元組處停止。
8.0.0 length 現在可以為 null。

範例

範例 #1 strcspn() 範例

<?php
$a
= strcspn('banana', 'a');
$b = strcspn('banana', 'abcd');
$c = strcspn('banana', 'z');
$d = strcspn('abcdhelloabcd', 'a', -9);
$e = strcspn('abcdhelloabcd', 'a', -9, -5);

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
?>

以上範例會輸出:

int(1)
int(0)
int(6)
int(5)
int(4)

注意事項

注意此函式是二進位安全的。

參見

  • strspn() - 尋找字串起始片段的長度,該片段完全由給定遮罩中包含的字元組成。

新增註解

使用者貢獻的註解 5 則註解

AT-HE (at_he AT hotmai1 DOT com)
18 年前
這個函式可以像 strspn() 一樣使用,不同的是 strspn() 可以用來將字串與允許的模式進行比較,而這個函式可以用來將字串與**禁止**的模式進行比較。

因此,要知道任何禁止字元是否在我們的字串中出現,我們可以使用(未經反斜線測試)...

<?php
// 完整版本
$forbidden="\"\\?*:/@|<>";
if (
strlen($filename) != strcspn($filename,$forbidden)) {
echo
"您不能使用該名稱建立檔案!";
}

// 簡短版本
if (strlen($filename) - strcspn($filename,"\"\\?*:/@|<>")) {
echo
"我告訴過您,您不能建立該檔案";
}
?>
maskedcoder at hotmail dot com
19 年前
用於在包含 HTML 的變數中查找引號和/或標籤的開頭。
$pos = strcspn($data, '<"\'');
將會找到標籤開頭、雙引號或單引號字串的第一個出現位置。
legacyprog at routinz dot net
13 年前
使用第三個參數時,請記住,該函數會返回它跳過的字元數,這\*並非\*原始字串中的位置。只需將第三個參數值添加到函數結果中,即可輕鬆修正並獲得掃描停止在第一個字串中的位置,但我一開始沒想到這點。
匿名
15 年前
strcspn() 也可以被認為類似於以下正則表達式
<?php
// 其中 ... 代表字元遮罩
preg_match('/[^ ...]/', substr($subject, $start, $length) );
?>
透過這種類比,strcspn() 可以取代一些正則表達式來匹配模式,而無需正則表達式引擎的額外開銷——例如,驗證輸入字串是否代表二進位值的方法
<?php
preg_match
('/^[01]+$/i', $subject);
// 或者...
!preg_match('/[^01]/i', $subject);

// ...或者使用 strcspn()
!strcspn($subject, '01');
?>
nospam at nospam dot com
8 年前
範例可能不太清楚,

strcspn('abcdhelloabcd', 'abcd', -9, -5) == 4

因為它只評估 'hell',其中不包含任何遮罩,所以返回 strlen('hell')。
To Top