您好,登錄后才能下訂單哦!
PHP中startsWith()和endsWith()函數(shù)如何使用,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
例如:
$str = '|apples}';echo startsWith($str, '|'); //Returns trueecho endsWith($str, '}'); //Returns true
上面的正則表達式功能,但上面提到的其他調整:
function startsWith($needle, $haystack) { return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack); } function endsWith($needle, $haystack) { return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack); }
簡而言之:
function startsWith($str, $needle){ return substr($str, 0, strlen($needle)) === $needle; }function endsWith($str, $needle){ $length = strlen($needle); return !$length || substr($str, - $length) === $needle; }
您可以使用substr_compare
函數(shù)來檢查start-with和ends-with:
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
是一個更快的觸摸開始 - 但它無法檢查結束。
為什么不以下?
//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 . "!"; }
輸出:
在valuehaystack開頭找到價值!
請記住,如果在大海撈針中找不到針, strpos
將返回false,并且當且僅當在指數(shù)0處找到針時才會返回0(AKA開頭)。
以下是:
$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 . "!"; }
在這種情況下,不需要函數(shù)startsWith()as
(strpos($stringToSearch, $doesItStartWithThis) === 0)
將準確地返回真或假。
這看起來很奇怪,所有狂野的功能在這里都很猖獗。
我意識到這已經完成了,但你可能想看一下 strncmp因為它允許你把字符串的長度進行比較,所以:
function startsWith($haystack, $needle, $case=true) { if ($case) return strncasecmp($haystack, $needle, strlen($needle)) == 0; else return strncmp($haystack, $needle, strlen($needle)) == 0; }
看完上述內容,你們掌握PHP中startsWith()和endsWith()函數(shù)如何使用的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。