Code前端首页关于Code前端联系我们

PHP8 提供了三种处理字符串的方法:str_contains()、str_starts_with()、str_ends_with(), WordPress 5.9提供了字符串函数polyfill

terry 2年前 (2023-09-25) 阅读数 60 #后端开发

PHP8引入了三种处理字符串的方法,分别是str_contains()str_starts_with()str_ends_with() ,任何人光看方法名就可以猜出这三个方法的作用,WordPress 5.9提供了这三个字符串函数polyfill。

PHP8处理字符串三个方法:str_contains()、 str_starts_with()、 str_ends_with(),WordPress 5.9 提供字符串函数 polyfill

polyfill 意味着即使你服务器的 PHP 版本不是 8.0 版本,WordPress 本身也实现了这三个功能。只要你有 WordPress 5.9 版本,你就可以完全放心使用 str_contains()str_starts_with()str_ends_with()这三个函数。

str_contains

检测字符串是否包含另一个子字符串。

在PHP7中我们一般使用strpos方法来检测,但使用起来总是不够直观。你经常需要搜索文档来理解它的含义,这并不容易,特别是对于新手程序员来说。去理解。

str_contains(string $haystack, string $needle): bool

如果使用str_contains函数,请注意英文区分大小写。此外,如果 $needle 为空,则返回 true

WordPress 5.9 str_contains polyfill:

if ( ! function_exists( 'str_contains' ) ) {
	function str_contains( $haystack, $needle ) {
		return ( '' === $needle || false !== strpos( $haystack, $needle ) );
	}
}

str_starts_with 和 str_ends_with

这个函数非常相似。第一个是检测一个字符串是否以另一个字符串开头,第二个是结尾。

在PHP7中我们经常使用substr_comparestrpos来实现相应的功能。这样的代码不够直观,效率也不高。

str_starts_with(string $haystack, string $needle): bool
str_ends_with(string $haystack, string $needle): bool

这两个功能也是一样的。它们对于英语区分大小写。此外,如果 $needle 为空,则返回 true,它可以解释为以零字符开头的任何字符串。该字符串以零字符开头和结尾。

WordPress 5.9 str_starts_withstr_ends_with polyfill:

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 );
	}
}

array_key_first 和 array_key_last 函数

在 PHP 7.2 中,使用 reset(), 等方法如end()和key()用于通过改变数组内部指针来获取数组首尾的键和值。为了避免这种内部干扰,PHP 7.3引入了一个新函数来解决这个问题:

$key = array_key_first($array); 获取数组第一个元素的键名
​​ $ key = array_key_last($array);获取数组最后一个元素的键名

我之前在WPJAM Basic中实现了这两个函数的polyfill,现在WordPress 5.9也实现了这两个函数的polyfill :

if ( ! function_exists( 'array_key_first' ) ) {
	function array_key_first( array $arr ) {
		foreach ( $arr as $key => $value ) {
			return $key;
		}
	}
}
if ( ! function_exists( 'array_key_last' ) ) {
	function array_key_last( array $arr ) {
		if ( empty( $arr ) ) {
			return null;
		}
		end( $arr );
		return key( $arr );
	}
}

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门