php8新增的字符串函数

php8新增的字符串函数

苏苏
2023-06-07 / 0 评论 / 8 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年06月07日,已超过786天没有更新,若内容或图片失效,请留言反馈。

在php7,一直都是自己写文字包含、文字开始、文字结束函数,php8开始,终于内置了这三个函数。

str_contains

  • 功能:确定字符串是否包含指定子串
  • 语法: str_contains(string $haystack, string $needle): bool
  • 参数: haystack 在其中搜索的字符串; needle 要在 haystack 中搜索的子串。
  • 返回值:如果 needlehaystack 中,返回 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 中搜索的子串。
  • 返回值:如果 haystackneedle 开头,返回 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 中搜索的子串。
  • 返回值:如果 haystackneedle 结尾,返回 true ,否则返回 false
  • 是否区分大小写:是

示例 使用空字符串 '':

if (str_ends_with('abc', '')) {
    echo "All strings end with the empty string";
}

以上示例会输出:

All strings end with the empty string

参考文档:

  1. https://www.php.net/manual/zh/function.str-contains
  2. https://www.php.net/manual/zh/function.str-starts-with.php
  3. https://www.php.net/manual/zh/function.str-ends-with.php
0

评论 (0)

取消