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

我如何編寫兩個帶字符串的函數,若是它以指定的字符/字符串開頭或以它結尾,則返回? php

例如: git

$str = '|apples}';

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

#1樓

上面的正則表達式功能,但上面提到的其餘調整: github

function startsWith($needle, $haystack) {
     return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
 }

 function endsWith($needle, $haystack) {
     return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
 }

#2樓

簡而言之: 正則表達式

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

function endsWith($str, $needle){
   $length = strlen($needle);
   return !$length || substr($str, - $length) === $needle;
}

#3樓

您能夠使用substr_compare函數來檢查start-with和ends-with: app

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是一個更快的觸摸開始 - 但它沒法檢查結束。 函數


#4樓

爲何不如下? 測試

//How to check if a string begins with another string
$haystack = "valuehaystack";
$needle = "value";
if (strpos($haystack, $needle) === 0){
    echo "Found " . $needle . " at the beginning of " . $haystack . "!";
}

輸出: spa

在valuehaystack開頭找到價值! .net

請記住,若是在大海撈針中找不到針, strpos將返回false,而且當且僅當在指數0處找到針時纔會返回0(AKA開頭)。 code

如下是:

$haystack = "valuehaystack";
$needle = "haystack";

//If index of the needle plus the length of the needle is the same length as the entire haystack.
if (strpos($haystack, $needle) + strlen($needle) === strlen($haystack)){
    echo "Found " . $needle . " at the end of " . $haystack . "!";
}

在這種狀況下,不須要函數startsWith()as

(strpos($stringToSearch, $doesItStartWithThis) === 0)

將準確地返回真或假。

這看起來很奇怪,全部狂野的功能在這裏都很猖獗。


#5樓

我意識到這已經完成了,但你可能想看一下strncmp由於它容許你把字符串的長度進行比較,因此:

function startsWith($haystack, $needle, $case=true) {
    if ($case)
        return strncasecmp($haystack, $needle, strlen($needle)) == 0;
    else
        return strncmp($haystack, $needle, strlen($needle)) == 0;
}
相關文章
相關標籤/搜索