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

我该如何编写两个函数,如果它以指定的字符/字符串开头或者以它结束,则返回一个字符串并返回?

例如:

$str = '|apples}';

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

function startsWith($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function endsWith($haystack, $needle)
{
    $length = strlen($needle);

    return $length === 0 || 
    (substr($haystack, -$length) === $needle);
}

如果你不想使用正则表达式,请使用它。


可以分别使用strrposstrpos来检查start-with和ends。

请注意,使用strrpos来检查开始与strpos来检查结束将尽快返回而不是检查整个字符串直到结束。 此外,此解决方案不会创建临时字符串。 考虑解释之前的原因downvoting。 仅仅因为DWTF的f-wit不明白这个函数是如何工作的,或者认为只有一个解决方案并不意味着这个答案是错误的。

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}

function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}

测试和结果(与此相比较):

startsWith("abcdef", "ab") -> true
startsWith("abcdef", "cd") -> false
startsWith("abcdef", "ef") -> false
startsWith("abcdef", "") -> true
startsWith("", "abcdef") -> false

endsWith("abcdef", "ab") -> false
endsWith("abcdef", "cd") -> false
endsWith("abcdef", "ef") -> true
endsWith("abcdef", "") -> true
endsWith("", "abcdef") -> false

注意: strncmpsubstr_compare函数将胜过此函数。


2016年8月23日更新

功能

function substr_startswith($haystack, $needle) {
    return substr($haystack, 0, strlen($needle)) === $needle;
}

function preg_match_startswith($haystack, $needle) {
    return preg_match('~' . preg_quote($needle, '~') . '~A', $haystack) > 0;
}

function substr_compare_startswith($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
}

function strpos_startswith($haystack, $needle) {
    return strpos($haystack, $needle) === 0;
}

function strncmp_startswith($haystack, $needle) {
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}

function strncmp_startswith2($haystack, $needle) {
    return $haystack[0] === $needle[0]
        ? strncmp($haystack, $needle, strlen($needle)) === 0
        : false;
}

测试

echo 'generating tests';
for($i = 0; $i < 100000; ++$i) {
    if($i % 2500 === 0) echo '.';
    $test_cases[] = [
        random_bytes(random_int(1, 7000)),
        random_bytes(random_int(1, 3000)),
    ];
}
echo "done!n";


$functions = ['substr_startswith', 'preg_match_startswith', 'substr_compare_startswith', 'strpos_startswith', 'strncmp_startswith', 'strncmp_startswith2'];
$results = [];

foreach($functions as $func) {
    $start = microtime(true);
    foreach($test_cases as $tc) {
        $func(...$tc);
    }
    $results[$func] = (microtime(true) - $start) * 1000;
}

asort($results);

foreach($results as $func => $time) {
    echo "$func: " . number_format($time, 1) . " msn";
}

结果(PHP 7.0.9)

(排序最快到最慢)

strncmp_startswith2: 40.2 ms
strncmp_startswith: 42.9 ms
substr_compare_startswith: 44.5 ms
substr_startswith: 48.4 ms
strpos_startswith: 138.7 ms
preg_match_startswith: 13,152.4 ms

结果(PHP 5.3.29)

(排序最快到最慢)

strncmp_startswith2: 477.9 ms
strpos_startswith: 522.1 ms
strncmp_startswith: 617.1 ms
substr_compare_startswith: 706.7 ms
substr_startswith: 756.8 ms
preg_match_startswith: 10,200.0 ms

startswith_benchmark.php

链接地址: http://www.djcxy.com/p/4511.html

上一篇: startsWith() and endsWith() functions in PHP

下一篇: Why Magic Quotes has been removed from PHP 5.4?