php with函数,PHP中的startsWith()和endsWith()函数

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

例如:

$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;

}

您可以使用

函数来检查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)

将准确地返回真或假。

这看起来很奇怪,所有狂野的功能在这里都很猖獗。

我意识到这已经完成了,但你可能想看一下

因为它允许你把字符串的长度进行比较,所以:

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、付费专栏及课程。

余额充值