Php string starts and ends with

How to Use the StartsWith() and EndsWith() Functions in PHP

Sometimes, while working with PHP, it is necessary to test whether a string starts/ends with a particular character/string or not. For that purpose, the startsWith() and endsWith() functions are used. On this page, we will show you how they work and how you can use them efficiently.

StartsWith()

The startsWith() function is generally applied for detecting whether a string starts at a particular string or not. It is a case-insensitive function and is capable of returning a boolean value. To look for data, you can use it along with the filter function.

The syntax of startsWith() is the following:

bool startsWith( string, startString )

Two parameters are accepted by this function: string and startString . The first parameter is applied for holding the text that needs to be tested. The second one is the text to look for at the beginning of the String. Once it’s an empty string, it will return true.

On success the startsWith() function returns true, otherwise, false. Here is an example of returning false:

 // Function for checking the string starting // with a particular substring function startsWith($string, $startString) < $len = strlen($startString); return substr($string, 0, $len) === $startString; > // Main function if (startsWith("abcde", "c")) < echo "True"; > else < echo "False"; > ?>

In the example below, true is returned:

 // Function for checking the string starting // with a particular substring function startsWith($string, $startString) < $len = strlen($startString); return substr($string, 0, $len) === $startString; > // Main function if (startsWith("abcde", "a")) < echo "True"; > else < echo "False"; > ?>

EndsWith()

The endsWith() function is similar to the startsWith() function, but it is applied for testing whether a string ends with a certain string or not. This function is also case insensitive, returning a boolean value. You can use it along with the Filter function for searching data.

The syntax of endsWith() looks like this:

bool endsWith( string, endString )

It includes the following two parameters: string and endString. The first parameter is applied for holding the text that needs to be tested. The second one is the text to look for at the end of the String. It can return true or false, as shown in the examples below:

 // Function for checking the string ends // with a particular substring or not function endsWith($string, $endString) < $len = strlen($endString); if ($len == 0) < return true; > return substr($string, -$len) === $endString; > // Driver code if (endsWith("abcde", "de")) < echo "True"; > else < echo "False"; > ?> ?php // Function for checking the string ends // with a particular substring or not function endsWith($string, $endString) < $len = strlen($endString); if ($len == 0) < return true; > return (substr($string, -$len) === $endString); > // Driver code if(endsWith("abcde","dgfe")) echo "True"; else echo "False"; ?>

So, these functions are among the most commonly used ones in PHP. Learning how to use them will significantly enhance your success while working with PHP.

Источник

PHP RFC: Add str_starts_with() and str_ends_with() functions

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 Symfony, Laravel, Yii, FuelPHP, and Phalcon 1) .

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 ) ” 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.

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.

$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 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 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 .

Источник

PHP RFC: Add str_starts_with(), str_ends_with() and related functions

PHP does not contain functions to test if a string begins or ends with a certain substring. This is currently possible using several other functions, but adding pre-built functions to do this will improve the readability and clarity of PHP code using the function. This feature has been requested multiple times and would be of use to many PHP developers with varying levels of experience.

Proposal

Add str_starts_with(), str_starts_with_ci(), str_ends_with(), str_ends_with_ci(), mb_str_starts_with(), mb_str_starts_with_ci(), mb_str_ends_with(), and mb_str_ends_with_ci() functions:

function str_starts_with(string $haystack, string $needle): bool function str_starts_with_ci(string $haystack, string $needle): bool function str_ends_with(string $haystack, string $needle): bool function str_ends_with_ci(string $haystack, string $needle): bool function mb_str_starts_with(string $haystack, string $needle [, string $encoding]): bool function mb_str_starts_with_ci(string $haystack, string $needle [, string $encoding]): bool function mb_str_ends_with(string $haystack, string $needle [, string $encoding]): bool function mb_str_ends_with_ci(string $haystack, string $needle [, string $encoding]): bool

str_starts_with() checks if $haystack begins with $needle. It accomplishes this by comparing each character in $haystack with the corresponding character in $needle. If any of the characters do not match, it will return false. str_ends_with() does the same thing except in reverse: it starts at the end of both $haystack and $needle and compares each character in $haystack to the corresponding character in $needle.

str_starts_with_ci() and str_ends_with_ci() do the same thing, except they are case insensitive.

The mb_* versions of these method function very similar except they make use of the mbfl_strpos() function or the php_mb_stripos() helper function.

$str = "beginningMiddleEnd"; if (str_starts_with($str, "beg")) echo "This condition would be true"; if (str_starts_with($str, "Beg")) echo "This condition would not be true"; if (str_starts_with_ci($str, "beg")) echo "This condition would be true"; if (str_starts_with_ci($str, "Beg")) echo "This condition would also be true"; if (str_ends_with($str, "End")) echo "This condition would be true"; if (str_ends_with($str, "end")) echo "This condition would not be true"; if (str_ends_with_ci($str, "End")) echo "This condition would be true"; if (str_ends_with_ci($str, "end")) echo "This condition would also be true";

Backward Incompatible Changes

This could break functions existing in userland with the same names.

Proposed PHP Version(s)

Next eligible PHP 7.x release.

Источник

How to check if a PHP string begins or ends with a specific string

Posted on Aug 01, 2022

  • The str_starts_with() function allows you to check if a string starts with a specific string
  • The str_ends_with() function allows you to check if a string ends with a specific string

The functions will return a boolean value true or false depending on the result.

Here’s how to check if the string Hello World! starts with he :

The functions are case-sensitive, so they will return false when the case doesn’t match between the $string and $substring .

Here’s an example of checking the end of the string with str_ends_with() :

Note that the two functions above won’t be available when you’re using PHP below version 8.0.

You need to create your own custom functions to do the same.

Creating PHP functions to check for a string start and end substrings

In PHP version 7, you will have Call to undefined function error when calling str_starts_with() and str_ends_with() functions.

You need to create these functions manually with the help of strlen() and substr() functions:

    Here’s the test result of the str_starts_with() function above:

For the str_ends_with() function, you need to change the substr() parameter.

See the following code snippet:

  The str_ends_with() function produces the following result:

With the functions above, you can check if a string starts with or ends with a certain substring in PHP 7.

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Читайте также:  Fatal error in launcher unable to create process using python exe pip exe
Оцените статью