search
HomeBackend DevelopmentPHP TutorialPHP8.1's new str_contains function: quickly determine whether a substring exists

PHP8.1’s new str_contains function: quickly determine whether a substring exists

In the latest PHP8.1 version, a very convenient function str_contains has been added, its function is to Quickly determine whether a string contains another substring. Compared with the previous strpos function, the str_contains function is more concise and easy to use, which can greatly improve development efficiency. This article will introduce you to the use of str_contains function and provide some code examples.

In previous versions, to determine whether a string contains another substring, the strpos function was often used. For example, if we want to determine whether the string $str contains the substring "world", we can achieve this through the following code:

if(strpos($str, 'world') !== false){
    echo "包含子字符串";
}else{
    echo "不包含子字符串";
}

The above code first uses the strpos function to find the substring in the string. position, if the return value is not false, it means that the substring exists in the string, and we can output "contains substring". Otherwise, output "does not contain substring".

However, there are some problems with using the strpos function for judgment. First, the return value of the strpos function may be 0, indicating that the substring appears at the beginning of the string, which can be confused with the return value when the substring does not exist. Secondly, the strpos function requires writing more code to implement judgment, which does not seem intuitive enough. Therefore, in the new version of PHP8.1, the str_contains function was introduced to solve these problems.

The use of the str_contains function is very simple. You only need to pass in two parameters. The first parameter is the string to be searched, and the second parameter is the substring to be searched. The function returns a bool value indicating whether the substring exists in the string.

The following is a sample code using the str_contains function:

$str = "Hello, world!";
if(str_contains($str, 'world')){
    echo "包含子字符串";
}else{
    echo "不包含子字符串";
}

In the above code, if the string $str contains the substring "world", then "contains substring" is output; otherwise , output "does not contain substring". It can be seen that compared to using the strpos function, using the str_contains function is more intuitive and concise.

In addition to being used to determine whether a single string contains a substring, the str_contains function can also be used for each element in an array or string. The following is a sample code:

$fruits = ['apple', 'banana', 'orange'];
if(str_contains($fruits, 'banana')){
    echo "数组中包含子字符串";
}else{
    echo "数组中不包含子字符串";
}

In the above code, determine whether the array $fruits contains the substring "banana". If it does, output "the array contains the substring"; otherwise, output "array" does not contain substring".

In summary, the new str_contains function in PHP8.1 provides us with a simple and intuitive way to determine whether a string contains substrings. Its use is very simple, you only need to pass in two parameters and determine the return value. Whether you are testing a single string or each element in an array or string, the str_contains function provides a convenient solution. When you start using PHP8.1 version, remember to try this convenient function!

The above is the detailed content of PHP8.1's new str_contains function: quickly determine whether a substring exists. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools