php string starts with
PHP RFC: Add str_starts_with() and str_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.
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.
str_starts_with
This is memory inefficient because it requires an unnecessary copy of part of the haystack.
This is potentially CPU inefficient because it will unnecessarily search along the whole haystack if it doesn’t find the needle.
str_ends_with
This is memory inefficient (see above).
This is doubly inefficient because it requires reversing both the haystack and the needle as well as applying strpos (see above).
This is verbose and also potentially CPU inefficient.
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 :
Note: the behavior concerning empty strings is in accordance with what is described in the accepted str_contains RFC. This behavior is also the same as is common with other languages, including Java and Python.
Backward Incompatible Changes
verify, if the string starts with given substring
How can I verify if it starts with some word?
When I wrote the following script returns yes
BUT it returns yes even when I wrote
I think strpos returns zero if it can’t find substring too (or a value that evaluates to zero).
So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?
10 Answers 10
You should check with the identity operator (===), see the documentation.
As @Samuel Gfeller pointed out: As of PHP8 you can use the str_starts_with() method. You can use it like this:
PHP does have 2 functions to verify if a string starts with a given substring:
So if you want to test only http (and not https), you can use:
as == will turn positive for both false & 0 check the documentation
Is a bit more performant than strpos
Starting with PHP 8 (2020-11-24), you can use str_starts_with:
PHP 8 has now a dedicated function str_starts_with for this.
There’s a big red warning in the documentation about this:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or «». Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to check if a string starts with a specified string? [duplicate]
5 Answers 5
PHP 8 or newer:
PHP 7 or older:
Use the substr function to return a part of a string.
If you’re trying to make sure it’s not another protocol. I’d use http:// instead, since https would also match, and other things such as http-protocol.com.
Remember the three equals signs ( === ). It will not work properly if you only use two. This is because strpos() will return false if the needle cannot be found in the haystack.
There is also the strncmp() function and strncasecmp() function which is perfect for this situation:
The advantage over the substr() approach is that strncmp() just does what needs to be done, without creating a temporary string.
You can use a simple regex (updated version from user viriathus as eregi is deprecated)
or if you want a case insensitive search
Regexes allow to perform more complex tasks
Performance wise, you don’t need to create a new string (unlike with substr) nor parse the whole string if it doesn’t start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).
PHP 8.0: New str_starts_with and str_ends_with functions
PHP 8.0 comes with two new functions to help you easily assert if a given string is present at the beginning or ending of a haystack string. This goes nicely with str_contains() in PHP 8.0.
Case sensitivity
Both str_starts_with() and str_ends_with() functions are case-sensitive. There are no flags or other functions to make them case-insensitive. This is the same pattern with str_contains
Multi-byte strings
Multi-byte ( mb_* ) variants for str_starts_with() and str_ends_with() are not currently planned.
Empty strings
As of PHP 8, behavior of » in string search functions is well defined, and
we consider » to occur at every position in the string, including one past
the end. As such, both of these will (or at least should) return true. The
empty string is contained in every string.
The following calls will be always true:
Polyfills
Here is a polyfill for PHP 7.0 and later. Be sure to wrap them with function_exists() calls where you use them. These functions pass the exact same tests in PHP core.
Conflicts with current user-land implementations
There are over 4,000 str_starts_with() matches on GitHub, for PHP, most of which appear to be already namespaced.
Case-insensitivity support | Empty strings at every position | |
---|---|---|
PHP 8.0 str_starts_with str_ends_with | No | Yes |
Polyfill (above) str_starts_with str_ends_with | No | Yes |
Symfony String ::startsWith ::endsWith | Yes With ::ignoreCase() | No |
Laravel Str::startsWith Str::endsWith | No | No |
Yii StringHelper::startsWith StringHelper::endsWith | Yes (default) With parameter | No |
Backwards compatibility impact
Both str_starts_with and str_ends_with functions are new functions. Unless you already have a str_contains() function declared, there should be no BC impact.
Php string starts with
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.
The complex syntax can be recognised by the curly braces surrounding the expression.
Simple syntax
The above example will output:
Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket ( ] ) marks the end of the index. The same rules apply to object properties as to simple variables.
Example #15 Simple syntax example
$people = new people ();
The above example will output:
As of PHP 7.1.0 also negative numeric indices are supported.
Example #16 Negative numeric indices
The above example will output:
For anything more complex, you should use the complex syntax.
Complex (curly) syntax
This isn’t called complex because the syntax is complex, but because it allows for the use of complex expressions.
// Show all errors
error_reporting ( E_ALL );
echo «This is the value of the var named by the return value of getName(): <$< getName ()>> » ;
// Won’t work, outputs: This is the return value of getName():
echo «This is the return value of getName():
?>
It is also possible to access class properties using variables within strings using this syntax.
The above example will output:
The value accessed from functions, method calls, static class variables, and class constants inside <$>will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ( <> ) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
// Show all errors.
error_reporting ( E_ALL );
$rootbeer = ‘A & W’ ;
$ipa = ‘Alexander Keith\’s’ ;
String access and modification by character
Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted E_NOTICE for reading (yielding an empty string) and E_WARNING for writing (leaving the string untouched).
Internally, PHP strings are byte arrays. As a result, accessing or modifying a string using array brackets is not multi-byte safe, and should only be done with strings that are in a single-byte encoding such as ISO-8859-1.
Note: As of PHP 7.1.0, applying the empty index operator on an empty string throws a fatal error. Formerly, the empty string was silently converted to an array.
Example #17 Some string examples
String offsets have to either be integers or integer-like strings, otherwise a warning will be thrown.
Example #18 Example of Illegal String Offsets
The above example will output:
Accessing characters within string literals using the <> syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
Useful functions and operators
String s may be concatenated using the ‘.’ (dot) operator. Note that the ‘+’ (addition) operator will not work for this. See String operators for more information.
There are a number of useful functions for string manipulation.
See the string functions section for general functions, and the Perl-compatible regular expression functions for advanced find & replace functionality.
There are also functions for URL strings, and functions to encrypt/decrypt strings (Sodium and Hash).
Converting to string
An int or float is converted to a string representing the number textually (including the exponent part for float s). Floating point numbers can be converted using exponential notation ( 4.1E+6 ).
In order to convert object s to string magic method __toString must be used.
null is always converted to an empty string.
Most PHP values can also be converted to string s for permanent storage. This method is called serialization, and is performed by the serialize() function.
Details of the String Type
The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)
This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.
Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string «á» equivalent to «\xE1» (ISO-8859-1), «\xC3\xA1» (UTF-8, C form), «\x61\xCC\x81» (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicitly declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.
Of course, in order to be useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:
Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.