温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP中startsWith()和endsWith()函数如何使用

发布时间:2021-07-14 16:18:03 来源:亿速云 阅读:140 作者:Leah 栏目:编程语言

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

您可以使用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;
}

看完上述内容,你们掌握PHP中startsWith()和endsWith()函数如何使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI