====== PHP RFC: Add str_starts_with() and str_ends_with() functions ====== * Version: 0.5 * Date: 2020-03-25 (**Updated**: 2020-05-05) * Author: Will Hudgins, will@wkhudgins.info * Status: Implemented * First Published at: https://wiki.php.net/rfc/add_str_starts_with_and_ends_with_functions ===== Introduction ===== ''str_starts_with'' checks if a string begins with another string and returns a boolean value (''true''/''false'') whether it does.\\ ''str_ends_with'' checks if a string ends with another string and returns a boolean value (''true''/''false'') whether it does. Typically this functionality is accomplished by using existing string functions such as substr, strpos/strrpos, strncmp, or substr_compare (often combined with strlen). These bespoke userland implementations have various downsides, discussed further below. The ''str_starts_with'' and ''str_ends_with'' functionality is so commonly needed that many major PHP frameworks support it, including [[https://symfony.com/doc/5.0/components/string.html#methods-to-search-and-replace|Symfony]], [[https://laravel.com/docs/7.x/helpers#method-starts-with|Laravel]], [[https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#startsWith()-detail|Yii]], [[https://fuelphp.com/docs/classes/str.html#/method_starts_with|FuelPHP]], and [[https://docs.phalcon.io/3.4/en/api/phalcon_text|Phalcon]] ((some of those links are for ''str_starts_with'' functionality, but the mentioned frameworks also contain ''str_ends_with'' functionality, often visible on the same web page)). Checking the start and end of strings is a very common task which should be easy. Accomplishing this task is not easy now and that is why many frameworks have chosen to include it. This is also why other high-level programming languages---as diverse as JavaScript, Java, Haskell, and Matlab---have implemented this functionality. Checking the start and end of a string should not be a task which requires pulling in a PHP framework or developing a potentially suboptimal (or worse, buggy) function in userland. ==== Downsides of Common Userland Approaches ===== Ad hoc userland implementations of this functionality are __less intuitive__ than dedicated functions (this is especially true for new PHP developers and developers who frequently switch between PHP and other languages---many of which include this functionality natively).\\ The implementation is also __easy to get wrong__ (especially with the ''==='' comparison).\\ Additionally, there are __performance issues__ with many userland implementations. //Note: some implementations add "//$needle === "" || //" and/or "//strlen($needle) <= strlen($haystack) && //" guards to handle empty needle values and/or avoid warnings.// === str_starts_with === substr($haystack, 0, strlen($needle)) === $needle This is memory inefficient because it requires an unnecessary copy of part of the haystack. strpos($haystack, $needle) === 0 This is potentially CPU inefficient because it will unnecessarily search along the whole haystack if it doesn't find the needle. strncmp($haystack, $needle, strlen($needle)) === 0 // generic strncmp($subject, "prefix", 6) === 0 // ad hoc This is efficient but requires providing the needle length as a separate argument, which is either verbose (repeat "''$needle''") or error prone (hard-coded number). === str_ends_with === substr($haystack, -strlen($needle)) === $needle This is memory inefficient (see above). strpos(strrev($haystack), strrev($needle)) === 0 This is doubly inefficient because it requires reversing both the haystack and the needle as well as applying ''strpos'' (see above). strrpos($haystack, $needle) === strlen($haystack) - strlen($needle) This is verbose and also potentially CPU inefficient. substr_compare($haystack, $needle, -strlen($needle)) === 0 // generic substr_compare($subject, "suffix", -6) === 0 // ad hoc This is efficient but either verbose or error prone (see ''strncmp'' above). ===== Proposal ===== Add two new basic functions: ''str_starts_with'' and ''str_ends_with'': str_starts_with ( string $haystack , string $needle ) : bool str_ends_with ( string $haystack , string $needle ) : bool ''str_starts_with()'' checks if ''$haystack'' begins with ''$needle''. If ''$needle'' is longer than ''$haystack'', it returns ''false''; else, it compares each character in ''$needle'' with the corresponding character in ''$haystack'' (aligning both strings at their start), returning ''false'' if it encounters a mismatch, and ''true'' otherwise.\\ ''str_ends_with()'' does the same thing but aligning both strings at their end. Examples below: $str = "beginningMiddleEnd"; if (str_starts_with($str, "beg")) echo "printed\n"; if (str_starts_with($str, "Beg")) echo "not printed\n"; if (str_ends_with($str, "End")) echo "printed\n"; if (str_ends_with($str, "end")) echo "not printed\n"; // empty strings: if (str_starts_with("a", "")) echo "printed\n"; if (str_starts_with("", "")) echo "printed\n"; if (str_starts_with("", "a")) echo "not printed\n"; if (str_ends_with("a", "")) echo "printed\n"; if (str_ends_with("", "")) echo "printed\n"; if (str_ends_with("", "a")) echo "not printed\n"; Note: the behavior concerning empty strings is in accordance with what is described in the accepted [[rfc:str_contains#proposal|str_contains RFC]]. This behavior is also the same as is common with other languages, including Java and Python. ===== Backward Incompatible Changes ===== This could break functions existing in userland with the same names. But see [[rfc:str_contains#backward_incompatible_changes|the corresponding section in the str_contains RFC]] for a discussion illustrating how this concern may be mitigated and why it does not justify the rejection of this RFC. ===== Proposed PHP Version(s) ===== PHP 8 ===== RFC Impact ===== * **To SAPIs:** Will add the aforementioned functions to all PHP environments. * **To Existing Extensions:** None. * **To Opcache:** No effect. * **New Constants:** No new constants. * **php.ini Defaults:** No changed php.ini settings. ===== Votes ===== Voting closes 2020-05-04 * yes * no ===== Patches and Tests ===== * https://github.com/php/php-src/pull/5300 ===== Implementation ===== After the project is implemented, this section should contain - the version(s) it was merged to - a link to the git commit(s) - a link to the PHP manual entry for the feature ===== References ===== * Implementation of similar methods/functions in other languages: * JavaScript: [[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith|String#startsWith()]] and [[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith|String#endsWith()]] * Python: [[https://docs.python.org/3/library/stdtypes.html#str.startswith|str#startswith()]] and [[https://docs.python.org/3/library/stdtypes.html#str.endswith|str#endswith()]] * Java: [[https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)|String#startsWith()]] and [[https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#endsWith(java.lang.String)|String#endsWith()]] (and Apache Commons Lang [[https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#startsWith-java.lang.CharSequence-java.lang.CharSequence-|StringUtils.startsWith()]] and [[https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#endsWith-java.lang.CharSequence-java.lang.CharSequence-|StringUtils.endsWith()]]) * Ruby: [[https://ruby-doc.org/core-2.1.1/String.html#method-i-start_with-3F|String#start_with?()]] and [[https://ruby-doc.org/core-2.1.1/String.html#method-i-end_with-3F|String#end_with?()]] * Go: [[https://golang.org/pkg/strings/#HasPrefix|strings.HasPrefix()]] and [[https://golang.org/pkg/strings/#HasSuffix|strings.HasSuffix()]] * Haskell: [[https://hackage.haskell.org/package/MissingH-1.4.0.1/docs/Data-String-Utils.html#v:startswith|Data.String.Utils.startswith]] and [[https://hackage.haskell.org/package/MissingH-1.4.0.1/docs/Data-String-Utils.html#v:endswith|Data.String.Utils.endswith]] (aliases of [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:isPrefixOf|Data.List.isPrefixOf]] and [[https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:isSuffixOf|Data.List.isSuffixOf]]) * MATLAB: [[https://www.mathworks.com/help/matlab/ref/startswith.html|startsWith()]] and [[https://www.mathworks.com/help/matlab/ref/endswith.html|endsWith()]] * PHP feature request: [[bugid@50434]] (and duplicates: [[bugid@60630]], [[bugid@67035]], [[bugid@74449]]) * Accepted RFC for related function: [[rfc:str_contains|PHP RFC: str_contains]] * Rejected Prior RFC: [[rfc:add_str_begin_and_end_functions|PHP RFC: rfc:add_str_begin_and_end_functions]] * Discussion on the php.internals mailing list: [[https://externals.io/message/109318]] ===== Rejected Features ===== * **Case-insensitive** and **multibyte** variants were included in the previous version of this RFC, which was declined. See also [[rfc:str_contains#case-insensitivity_and_multibyte_strings|the related section in the str_contains RFC]].