您的位置 首页 php

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

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_compare strpos 来实现相应的功能,这样的代码不够直观,而且效率也不高。

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

这两个函数也是一样,对于英文,大小写敏感的,另外如果 $needle 为空,则返回 true ,可以理解为任何字符串以空字符串开始,也是以空字符结尾。

WordPress 5.9 str_starts_with str_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 );
}
}  

文章来源:智云一二三科技

文章标题:WordPress 5.9 提供了 PHP 8 新增的三个字符串函数的 polyfill

文章地址:https://www.zhihuclub.com/79772.shtml

关于作者: 智云科技

热门文章

网站地图