PHP 8 中新增了一个实用的字符串函数 str_starts_with()。本篇文章将介绍该函数的介绍、用法及示例。 str_starts_with() 函数可以判断一个字符串是否以另一个字符串开头,并返回布尔值,其语法如下: 参数解释: 返回值: 下面是一个示例,展示如何使用 str_starts_with() 函数: 除了上面的示例,我们还可以通过以下三个示例来进一步了解 str_starts_with() 函数的用法。 str_starts_with() 函数的加入弥补了 PHP 原生函数库中的一个短板,无疑会带来更高的生产力。在开发中,根据实际需要灵活运用该函数,会让你的代码更加简洁,更加易读易维护。 以上就是PHP8中的字符串函数:str_starts_with()如何使用的详细内容,更多请关注叶龍IT其它相关文章!str_starts_with() 的介绍
str_starts_with(string $haystack , string $needle): bool
$haystack
:要搜索的字符串。$needle
:被搜索的开头字符串。$haystack
以 $needle
开头,则返回 true。$haystack
不以 $needle
开头,则返回 false。str_starts_with() 的使用
<?php
$haystack = 'Hello World';
$needle = 'Hello';
if (str_starts_with($haystack, $needle)) {
echo "字符串 '{$haystack}' 以 '{$needle}' 开头。";
} else {
echo "字符串 '{$haystack}' 没有以 '{$needle}' 开头。";
}
// Output: 字符串 'Hello World' 以 'Hello' 开头。
str_starts_with() 的示例
示例一:不区分大小写
<?php
$haystack = 'Hello World';
$needle = 'hello';
if (str_starts_with(strtolower($haystack), strtolower($needle))) {
echo "字符串 '{$haystack}' 以 '{$needle}' 开头(不区分大小写)。";
} else {
echo "字符串 '{$haystack}' 没有以 '{$needle}' 开头(不区分大小写)。";
}
// Output: 字符串 'Hello World' 以 'hello' 开头(不区分大小写)。
示例二:判断两个 URL 是否匹配
<?php
$url = 'https://www.example.com';
$allowedUrls = ['https://www.example.com', 'https://www.example.org'];
foreach ($allowedUrls as $allowedUrl) {
if (str_starts_with($url, $allowedUrl)) {
echo "URL '{$url}' 被允许。";
}
}
// Output: URL 'https://www.example.com' 被允许。
示例三:判断文件扩展名是否匹配
<?php
$filename = 'example.php';
$allowedExtensions = ['php', 'html'];
foreach ($allowedExtensions as $extension) {
if (str_ends_with($filename, '.' . $extension)) {
echo "文件 '{$filename}' 合法,扩展名为 '{$extension}'。";
}
}
// Output: 文件 'example.php' 合法,扩展名为 'php'。
结论
发表评论 取消回复