3 ms·
> PHP to have str_contains() A function that checks if a string is contained in another string? That should only take about 25 years. For anyone else confused
by tzs 6y ago
> PHP to have str_contains() A function that checks if a string is contained in another string? That should only take about 25 years.
For anyone else confused by the newest thing on the list who is wondering what the heck str_contains() does that you could not already easily do with strstr() or strpos() since time immemorial, the answer is nothing.
The only difference between str_contains($needle, $haystack) and strstr($needle, $haystack) and strpos($needle, $haystack) is that after they all make exactly the same C function call:
php_memnstr(ZSTR_VAL(haystack), ZSTR_VAL(needle), ZSTR_LEN(needle), ZSTR_VAL(haystack) + ZSTR_LEN(haystack))
which returns either a pointer to the needle string in the haystack string or NULL,
• str_contains() return false or true, depending on whether that pointer is NULL or not,
• strstr() returns false or the part of haystack starting with needle, depending on whether that pointer is NULL or not, and
• strpos() returns false or the offset of needle within haystack, depending on whether that pointer is NULL or not.
It's equivalent to just writing (strpos(...) !== false) in your current code.
The rationale for adding str_compare() is that strstr() and strpos() are not intuitive, easy to get wrong, or hard for new developers to remember.
- Cthulhu_ 6y agoI personally don't object to 'trivial' functions sprinkled in my stdlib. I mean your own comment already highlights it, the return value of strstr() and strpos() is not intuitive, whereas you expect a boolean for a 'contains()' function. Of course, it also highlights one of PHP's often repeated criticisms, that of function naming inconsistency.