首页后端开发JAVAWordPress 5.9 提供了 PHP 8 新增的三个字符串函数的 polyfill

WordPress 5.9 提供了 PHP 8 新增的三个字符串函数的 polyfill

时间2023-04-21 22:39:01发布访客分类JAVA浏览777
导读:PHP8 引入 3 个处理字符串的方法,分别是 str_contains( 、 str_starts_with( 、 str_ends_with( ,大家一看方法名就已经猜到这三个方法的作用了,而 WordPress 5.9 提供了这三个字...

PHP8 引入 3 个处理字符串的方法,分别是 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 );

	}

}
    

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

php函数数组指针字符串

若转载请注明出处: WordPress 5.9 提供了 PHP 8 新增的三个字符串函数的 polyfill
本文地址: https://pptw.com/jishu/4771.html
WPJAM Basic 为什么要求 PHP 7.2 以上版本 WordPress 的 xmlrpc.php 经常被扫描,怎么办?

游客 回复需填写必要信息