PHP8 中如何移除字符串的前缀/后缀?函数没有?自己写两个

2022-06-2022:26:59后端程序开发Comments949 views字数 840阅读模式

PHP8 引入 3 个处理字符串的方法,分别是 str_contains()、 str_starts_with()、 str_ends_with(),大家一看方法名就已经猜到这三个方法的作用了,而 WordPress 5.9 提供了这三个字符串函数的 polyfill。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

polyfill 的意思是即使你服务器 PHP 版本没有 8.0 版本,WordPress 也自己实现了这三个函数,只要你的 WordPress 是 5.9 版本,就可以完全放心的使用 str_contains()、 str_starts_with()、 str_ends_with() 这三个函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

有时候我们判断了一个字符串以另一个字符串开头或者结尾之后,可能还需要移除这个前缀或者后缀,我找了一圈没有看到相应的 PHP 函数,所以就自己写了两个:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

移除字符串前缀

function wpjam_remove_prefix($str, $prefix){  if(str_starts_with($str, $prefix)){    return substr($str, strlen($prefix));  }
  return $str;}

先判断 $str 是否以 $prefix 开头,如果是,则移除它,使用很简单:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

wpjam_remove_prefix('wpjam_settings', 'wpjam_');  // 返回 settings

移除字符串后缀

function wpjam_remove_postfix($str, $postfix){  if(str_ends_with($str, $postfix)){    return substr($str, 0, strlen($str) - strlen($postfix));  }
  return $str;}

先判断 $str 是否以 $postfix 结尾,如果是,则移除它,使用很简单:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

wpjam_remove_postfix('get_fields_by_model', '_by_model');  // 返回 get_fields

作者:牛逼闪闪的Denis文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/24194.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/24194.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定