PHP Conference Japan 2024

str_ends_with

(PHP 8)

str_ends_with檢查字串是否以給定的子字串結尾

描述

str_ends_with(字串 $haystack, 字串 $needle): 布林值

執行區分大小寫的檢查,指出 haystack 是否以 needle 結尾。

參數

haystack

要搜尋的字串。

needle

要在 haystack 中搜尋的子字串。

傳回值

如果 haystackneedle 結尾,則傳回 true,否則傳回 false

範例

範例 1 使用空字串 ''

<?php
if (str_ends_with('abc', '')) {
echo
"所有字串都以空字串結尾";
}
?>

上述範例將輸出

All strings end with the empty string

範例 2 顯示區分大小寫

<?php
$string
= '那隻懶狐狸跳過柵欄';

if (
str_ends_with($string, '柵欄')) {
echo
"字串以 '柵欄' 結尾\n";
}

if (
str_ends_with($string, '柵欄')) {
echo
'字串以 "柵欄" 結尾';
} else {
echo
'"柵欄" 未找到,因為大小寫不符';
}

?>

上述範例將輸出

The string ends with 'fence'
"Fence" was not found because the case does not match

注意

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

參見

  • str_contains() - 判斷字串是否包含給定的子字串
  • str_starts_with() - 檢查字串是否以給定的子字串開頭
  • stripos() - 尋找字串中不區分大小寫子字串第一次出現的位置
  • strrpos() - 尋找字串中子字串最後一次出現的位置
  • strripos() - 尋找字串中不區分大小寫子字串最後一次出現的位置
  • strstr() - 尋找字串第一次出現的位置
  • strpbrk() - 在字串中搜尋任何一組字元
  • substr() - 傳回字串的一部分
  • preg_match() - 執行正規表示式比對

新增註解

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

9
javalc6 at gmail dot com
1 年前
如果您使用的是較舊版本的 PHP,您可以定義並使用以下函式

function endsWith($haystack, $needle) {
$length = strlen($needle);
return $length > 0 ? substr($haystack, -$length) === $needle : true;
}
8
Reinder
1 年前
在 PHP7 中,您可能想要使用

if (!function_exists('str_ends_with')) {
function str_ends_with($str, $end) {
return (@substr_compare($str, $end, -strlen($end))==0);
}
}

據我所知,這是二進位安全的,不需要額外檢查。
6
divinity76 at gmail dot com
3 年前
這是我能想到的最快的 php7 實作,它應該比 javalc6 和 Reinder 的實作更快,因為這個實作不會建立新的字串(但他們的會)

<?php
if (! function_exists('str_ends_with')) {
function
str_ends_with(string $haystack, string $needle): bool
{
$needle_len = strlen($needle);
return (
$needle_len === 0 || 0 === substr_compare($haystack, $needle, - $needle_len));
}
}
?>
To Top