我如何编写两个带字符串的函数,若是它以指定的字符/字符串开头或以它结尾,则返回? 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;
}