ITPub博客

首页 > 应用开发 > IT综合 > PHP中的startsWith()和endsWith()函数

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

原创 IT综合 作者:PHP大师 时间:2019-12-30 13:59:19 0 删除 编辑

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

例如:

$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函数来检查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,并且当且仅当在指数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 . "!";
}

在这种情况下,不需要函数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;
}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69957770/viewspace-2671226/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-12-19

  • 博文量
    8
  • 访问量
    4968