小编典典

PHP中的startsWith()和endsWith()函数

php

如果它以指定的字符/字符串开头或以指定的字符/字符串结尾,我如何编写两个接受字符串并返回的函数?

例如:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true

阅读 367

收藏
2022-02-20

共2个答案

小编典典

PHP 8.0 及更高版本

从 PHP 8.0 开始,您可以使用

str_starts_with Manual and

str_ends_with Manual

例子
echo str_starts_with($str, '|');

8.0 之前的 PHP

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;
}
2022-02-20
小编典典

您可以使用substr_compare函数来检查开头和结尾:

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 7(基准脚本)上最快的解决方案之一。针对 8KB 干草堆、各种长度的针以及完整、部分和不匹配的情况进行了测试。strncmp对于starts-with来说是一个更快的触摸,但它不能检查ends-with。

2022-02-20