如果您使用的是較舊版本的 PHP,您可以定義並使用以下函式
function endsWith($haystack, $needle) {
$length = strlen($needle);
return $length > 0 ? substr($haystack, -$length) === $needle : true;
}
(PHP 8)
str_ends_with — 檢查字串是否以給定的子字串結尾
haystack
要搜尋的字串。
needle
要在 haystack
中搜尋的子字串。
範例 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
注意:此函式是二進位安全的。
如果您使用的是較舊版本的 PHP,您可以定義並使用以下函式
function endsWith($haystack, $needle) {
$length = strlen($needle);
return $length > 0 ? substr($haystack, -$length) === $needle : true;
}
在 PHP7 中,您可能想要使用
if (!function_exists('str_ends_with')) {
function str_ends_with($str, $end) {
return (@substr_compare($str, $end, -strlen($end))==0);
}
}
據我所知,這是二進位安全的,不需要額外檢查。
這是我能想到的最快的 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));
}
}
?>