您好,欢迎访问一九零五行业门户网

PHP8中的字符串函数:str_starts_with()如何使用

php 8 中新增了一个实用的字符串函数 str_starts_with()。本篇文章将介绍该函数的介绍、用法及示例。
str_starts_with() 的介绍str_starts_with() 函数可以判断一个字符串是否以另一个字符串开头,并返回布尔值,其语法如下:
str_starts_with(string $haystack , string $needle): bool
参数解释:
$haystack:要搜索的字符串。$needle:被搜索的开头字符串。返回值:
如果 $haystack 以 $needle 开头,则返回 true。如果 $haystack 不以 $needle 开头,则返回 false。str_starts_with() 的使用下面是一个示例,展示如何使用 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() 的示例除了上面的示例,我们还可以通过以下三个示例来进一步了解 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'。
结论str_starts_with() 函数的加入弥补了 php 原生函数库中的一个短板,无疑会带来更高的生产力。在开发中,根据实际需要灵活运用该函数,会让你的代码更加简洁,更加易读易维护。
以上就是php8中的字符串函数:str_starts_with()如何使用的详细内容。
其它类似信息

推荐信息