PHP 8 was released in November 2020 and brought out a lot of new features and performance improvements. Let's learn some string-related functions available in PHP 8.
str_contains() functionPHP 8 proposes a new basic function, str_contains(), that checks if a string is contained in another string and returns a boolean value whether or not the string was found. The syntax looks like this:
<?phpstr_contains ( string $haystack, string $needle ) : bool;
The function takes two parameters, $haystack and $needle, and checks if the second parameter is found in the first one and returns true or false whether or not the $needle was found. Prior to PHP 8, we had to rely on strpos or ststr functions.
<?phpfunction containsStr(string $haystack, string $needle): bool {if (str_contains($haystack, $needle)) {return true;}}var_dump(containsStr('I learn on studytonight', 'studytonight'));
str_starts_with() functionPHP 8 comes with this new string-related function that checks if a given haystack string starts with the given needle string. The syntax looks almost the same as in str_contains():
<?phpstr_starts_with ( string $haystack, string $needle ) : bool;
<?phpvar_dump(str_starts_with('studytonight is so good', 'studytonight'));
str_ends_with() functionLike the previous function, this function checks if a given haystack string ends with the given needle string. Here’s an example:
<?phpvar_dump(str_ends_with('I learn on studytonight', 'studytonight'));
fdiv() functionPHP 8’s new fdiv() function fits along functions such as fmod() and intdiv() which allow for division by 0. Instead of errors, it returns INF, -INF or NAN depending on the case.
<?phpfdiv(1, 0); // float(INF)fdiv(-1, 0); // float(-INF)
Let's recap.
str_contains(): A boolean function that checks if a string is contained in another one.str_starts_with(): Another boolean function that checks if a string starts with a given string.str_ends_with(): A boolean function that checks if a string ends with the given string.fdiv(): Used for division by 0.