PHP中的str_starts_with和str_ends_with函数
技术背景
在PHP开发中,经常需要判断一个字符串是否以另一个字符串开头或结尾。在PHP 8.0之前,开发者需要自己实现这些功能,不同的实现方式在性能和兼容性上存在差异。而从PHP 8.0开始,官方提供了str_starts_with
和str_ends_with
函数,为字符串的开头和结尾判断提供了更便捷和高效的解决方案。
实现步骤
PHP 8.0及更高版本
在PHP 8.0及以上版本中,可以直接使用str_starts_with
和str_ends_with
函数。示例代码如下:
1 2
| var_dump(str_starts_with('|apples}', '|')); var_dump(str_ends_with('|apples}', '}'));
|
PHP 8.0之前的版本
在PHP 8.0之前,有多种实现方式,以下是几种常见的实现:
1 2 3 4 5 6 7 8 9 10 11 12
| function startsWith( $haystack, $needle ) { $length = strlen( $needle ); return substr( $haystack, 0, $length ) === $needle; }
function endsWith( $haystack, $needle ) { $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; }
|
1 2 3 4 5 6
| function startsWith($haystack, $needle) { return substr_compare($haystack, $needle, 0, strlen($needle)) === 0; } function endsWith($haystack, $needle) { return substr_compare($haystack, $needle, -strlen($needle)) === 0; }
|
核心代码
PHP 8.0及以上版本
1 2 3 4 5
| $str = "beginningMiddleEnd"; if (str_starts_with($str, "beg")) echo "printed\n"; if (str_starts_with($str, "Beg")) echo "not printed\n"; if (str_ends_with($str, "End")) echo "printed\n"; if (str_ends_with($str, "end")) echo "not printed\n";
|
PHP 8.0之前版本的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function startsWith( $haystack, $needle ) { $length = strlen( $needle ); return substr( $haystack, 0, $length ) === $needle; }
function endsWith( $haystack, $needle ) { $length = strlen( $needle ); if( !$length ) { return true; } return substr( $haystack, -$length ) === $needle; }
$haystack = "testString"; $needle = "test"; var_dump(startsWith($haystack, $needle)); var_dump(endsWith($haystack, "ing"));
|
最佳实践
- PHP 8.0及以上版本:优先使用
str_starts_with
和str_ends_with
函数,因为它们是官方提供的,性能和稳定性有保障。 - PHP 8.0之前版本:
- 如果对性能要求较高,可以使用
substr_compare
函数,它在某些情况下比substr
函数更快。 - 如果需要处理多字节字符串,建议使用
mb_substr
函数代替substr
函数。
常见问题
性能问题
不同的实现方式在性能上可能存在差异。例如,使用正则表达式虽然可以实现字符串开头和结尾的判断,但性能相对较低。可以通过基准测试来选择最适合的实现方式。
兼容性问题
在不同的PHP版本中,某些函数的行为可能会有所不同。例如,substr
函数在某些特殊情况下可能会返回false
,需要进行相应的处理。
多字节字符串问题
在处理多字节字符串时,普通的字符串处理函数可能无法正确处理。需要使用多字节字符串处理函数,如mb_strlen
和mb_substr
。