Home >Backend Development >PHP Tutorial >String functions in PHP8: How to use str_starts_with()
There is a new practical string function str_starts_with() in PHP 8. This article will introduce the introduction, usage and examples of this function.
str_starts_with() function can determine whether a string starts with another string and return a Boolean value. Its syntax is as follows:
str_starts_with(string $haystack , string $needle): bool
Parameter explanation:
$haystack
: The string to be searched. $needle
: The starting string being searched. Return value:
$haystack
starts with $needle
. $haystack
does not start with $needle
. The following is an example showing how to use the str_starts_with() function:
<?php $haystack = 'Hello World'; $needle = 'Hello'; if (str_starts_with($haystack, $needle)) { echo "字符串 '{$haystack}' 以 '{$needle}' 开头。"; } else { echo "字符串 '{$haystack}' 没有以 '{$needle}' 开头。"; } // Output: 字符串 'Hello World' 以 'Hello' 开头。
In addition to the above examples, we can also use the following three examples to further understand the usage of the str_starts_with() function.
<?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'。
The addition of str_starts_with() function makes up for a shortcoming in the PHP native function library and will undoubtedly bring higher productivity. During development, using this function flexibly according to actual needs will make your code more concise, easier to read and maintain.
The above is the detailed content of String functions in PHP8: How to use str_starts_with(). For more information, please follow other related articles on the PHP Chinese website!