老版本PHP 使用 str_starts_with 和 str_ends_with

江河/ 2023年07月18日/ PHP/ 浏览 751

PHP 8 中新增了 str_starts_with 和 str_ends_with 两个函数,使用起来非常方便。如果想在老版本的 PHP 中使用这两个函数,就只能自己定义一下了。


如下:


if ( ! function_exists( 'str_starts_with' ) ) {
	function str_starts_with( $haystack, $needle ) {
		if ( '' === $needle ) {
			return true;
		}

		return 0 === strpos( $haystack, $needle );
	}
}

if ( ! function_exists( 'str_ends_with' ) ) {
	function str_ends_with( $haystack, $needle ) {
		if ( '' === $haystack && '' !== $needle ) {
			return false;
		}

		$len = strlen( $needle );

		return 0 === substr_compare( $haystack, $needle, -$len, $len );
	}
}


上面的代码来自 WordPress 源码,但是貌似并未对外公开这两个函数,在 WordPress 文档中也找不到这两个函数。


实践中,最好是在 function.php 中添加上面两个函数的定义,然后才能放心使用。


发表评论

暂无评论,抢个沙发...

客服 工单