str_ends_with
檢查字符串是否以給定的子字符串結尾
函數名:str_ends_with()
適用版本:PHP 8.0.0 或更高版本
函數功能:判斷一個字符串是否以指定的後綴結尾
語法:bool str_ends_with ( string $haystack , string $needle )
參數:
返回值:
示例:
$string1 = "Hello, World!"; $string2 = "Hello, PHP!"; $suffix = "World!"; // 检查$string1 是否以$suffix 结尾if (str_ends_with($string1, $suffix)) { echo "$string1 以$suffix 结尾"; } else { echo "$string1 不以$suffix 结尾"; } // 检查$string2 是否以$suffix 结尾if (str_ends_with($string2, $suffix)) { echo "$string2 以$suffix 结尾"; } else { echo "$string2 不以$suffix 结尾"; }
輸出:
Hello, World! 以World! 结尾Hello, PHP! 不以World! 结尾
注意:在PHP 8.0.0 之前的版本中,可以使用類似的功能通過以下代碼實現:
function str_ends_with($haystack, $needle) { $length = strlen($needle); if ($length == 0) { return true; } return substr($haystack, -$length) === $needle; }
然而,使用PHP 8.0.0 及更高版本的內置函數str_ends_with() 可以提供更簡潔和高效的方式來判斷一個字符串是否以指定的後綴結尾。