New string methods in PHP8.0: str_starts_with and str_ends_with

New string methods in PHP8.0: str_starts_with and str_ends_with

PHP8.0 is the latest version of the PHP programming language, which brings many exciting new features and improvements. Among them, str_starts_with() and str_ends_with() are two very useful string methods. This article will introduce you to their functions, usage and examples.

str_starts_with() method

The str_starts_with() method is used to check whether a string starts with the specified substring, if so, it returns true, otherwise it returns false.

This is the syntax of str_starts_with() method:

bool str_starts_with ( string $haystack , string $needle )

其中,$haystack 参数是要检查的字符串,$needle 则是需要检查的子字符串。

Here are some examples of the str_starts_with() method:

Example 1:

To check if a string starts with the substring "Hello":

$myString = "Hello World";
if (str_starts_with($myString, "Hello")) {
    echo "字符串以 Hello 开头。";
} else {
    echo "字符串不以 Hello 开头。";
}

// 输出:"字符串以 Hello 开头。"

Example 2:

To check if a string starts with the number "123":

$myString = "123ABC";
if (str_starts_with($myString, "123")) {
    echo "字符串以 123 开头。";
} else {
   echo "字符串不以 123 开头。";
}

// 输出:"字符串以 123 开头。"

str_ends_with() method

The str_ends_with() method is used to check whether a string ends with the specified substring, if so, it returns true, otherwise it returns false.

This is the syntax of str_ends_with() method:

bool str_ends_with ( string $haystack , string $needle )

其中,$haystack 参数是要检查的字符串,$needle 则是需要检查的子字符串。

Here are some examples of the str_ends_with() method:

Example 1

To check if a string ends with the substring "World":

$myString = "Hello World";
if (str_ends_with($myString, "World")) {
     echo "字符串以 World 结尾。";
} else {
    echo "字符串不以 World 结尾。";
}

// 输出:"字符串以 World 结尾。"

Example 2

To check if a string ends with the substring "789":

$myString = "ABC789";
if (str_ends_with($myString, "789")) {
   echo "字符串以 789 结尾。";
} else {
   echo "字符串不以 789 结尾。";
}

// 输出:"字符串以 789 结尾。"

in conclusion

The str_starts_with() and str_ends_with() methods are very useful string methods in PHP8.0. They allow developers to more conveniently check the beginning and end of a string, thus improving the readability and performance of the code.

If you are using PHP8.0 or higher, it is strongly recommended that you learn these two methods and use them in your development projects.

da8f933a129e62cd511d8e2185b95a63.jpeg

Guess you like

Origin blog.csdn.net/lxw1844912514/article/details/132550971