php 8 中新增了一个实用的字符串函数 str_starts_with()。本篇文章将介绍该函数的介绍、用法及示例。
str_starts_with() 函数可以判断一个字符串是否以另一个字符串开头,并返回布尔值,其语法如下:
str_starts_with(string $haystack , string $needle): bool
参数解释:
返回值:
下面是一个示例,展示如何使用 str_starts_with() 函数:
立即学习“PHP免费学习笔记(深入)”;
<?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' 开头(不区分大小写)。
<?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()如何使用的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号