php with函数,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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值