在php7,一直都是自己写文字包含、文字开始、文字结束函数,php8开始,终于内置了这三个函数。
str_contains
- 功能:确定字符串是否包含指定子串
- 语法:
str_contains(string $haystack, string $needle): bool
- 参数:
haystack
在其中搜索的字符串;needle
要在haystack
中搜索的子串。 - 返回值:如果
needle
在haystack
中,返回true
,否则返回false
。 - 是否区分大小写:是
示例1 使用空字符串 '':
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always return true";
}
以上示例会输出:
Checking the existence of the empty string will always return true
示例2 区分大小写:
$string = 'The lazy fox jumped over the fence';
if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}
if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}
以上示例会输出:
The string 'lazy' was found in the string
"Lazy" was not found because the case does not match
str_starts_with
- 功能:检查字符串是否以指定子串开头
- 语法:
str_starts_with(string $haystack, string $needle): bool
- 参数:
haystack
在其中搜索的字符串;needle
要在haystack
中搜索的子串。 - 返回值:如果
haystack
以needle
开头,返回true
,否则返回false
。 - 是否区分大小写:是
示例 使用空字符串 '':
if (str_starts_with('abc', '')) {
echo "All strings start with the empty string";
}
以上示例会输出:
All strings start with the empty string
str_ends_with
- 功能:检查字符串是否以指定子串结尾
- 语法:
str_ends_with(string $haystack, string $needle): bool
- 参数:
haystack
在其中搜索的字符串;needle
要在haystack
中搜索的子串。 - 返回值:如果
haystack
以needle
结尾,返回true
,否则返回false
。 - 是否区分大小写:是
示例 使用空字符串 '':
if (str_ends_with('abc', '')) {
echo "All strings end with the empty string";
}
以上示例会输出:
All strings end with the empty string
参考文档:
评论 (0)