伸手党有福了,PHP也能用上startsWith,endsWith 了
引言
写程序的时候经常会遇到这样的需求,判断某个字符串是否以某个子字符串开头或者结尾?一般你是怎么做的呢?每次都要手动写 substr 匹配?或者正则验证?是不是太麻烦了,就封装成 helper 函数。

这有点太 PHP 了,不行就来个函数。能不能优雅一些呢?本文就带你来看看。
学习时间
我们也先来造个轮子,看看其中一种的实现方法。先实现 startsWith 函数:
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
接着是 endsWith 函数:
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
原理都非常简单,除了字符串长度的验证,非法数据的验证。核心使用 substr 进行函数切割。切割长度就是子字符串的长度。如果完全相同,就是 true。
引申方法
我们说条条大道通罗马,php 实现功能也不仅仅一个办法。下面是使用内置函数 substr_compare 实现。该函数是二进制安全比较字符串,从偏移位置比较指定长度。具体形参就不具体贴出来了,大家看看手册,对比一下该函数的返回值。
下面直接贴代码。先是 startsWith 函数:
function startsWith($haystack, $needle) {
return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}
然后是 endsWith 函数:
function endsWith($haystack, $needle) {
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
是不是精简许多。一行代码实现,容错性还非常好。简直是NB!
优秀的框架
Laravel 5 为我们提供的 Str 类,也含有了 startsWith endsWith 方法。我们贴出来供大家对比:

我们看到,该方法第二个参数接受 string | array 数据,可以多个匹配。而且在数据类型上也做了强制转换,使得错误率更低,指向更明确。

写在最后
本文展示了 PHP 如何使用内置函数实现 startsWith / endsWith 方法。提供了 3 种方法,大家对比研究一下,哪种写法更健壮。
Haapy coding :_)
相关推荐
-
第18问:MySQL CPU 高了,怎么办?2025-02-24 10:27:18
-
mysql索引类型 normal, unique, full text
mysql索引类型 normal, unique, full text2025-02-24 10:05:05 -
uwsgi+django+nginx 搭建部分总结2025-02-24 10:03:33
-
使用Docker配置Nginx环境部署Nextcloud2025-02-24 10:02:03
-
Nginx安装和怎么使用2025-02-24 10:00:45