Tags
Asked 3 years ago
17 Jun 2021
Views 241
Iva

Iva posted

startsWith() and endsWith() functions in PHP

startsWith() and endsWith() functions in PHP
jignesh

jignesh
answered Apr 27 '23 00:00

In PHP, there is no built-in startsWith () or endsWith () function in the core string functions, but you can easily implement them using the sub str() function. Here are some examples of how to do that:

To implement startsWith ():



function startsWith($string, $prefix) {
    return substr($string, 0, strlen($prefix)) === $prefix;
}

This function takes two parameters: $string, which is the string you want to check, and $ prefix , which is the string you want to check if $ string starts with. The function uses substr () to extract a portion of $ string that is the same length as $ prefix , and then checks if that portion is equal to $prefix.

To implement endsWith ():



function endsWith($string, $suffix) {
    return substr($string, -strlen($suffix)) === $suffix;
}

This function takes two parameters: $ string , which is the string you want to check, and $ suffix , which is the string you want to check if $string ends with. The function uses substr () to extract a portion of $string that is the same length as $ suffix , starting from the end of the string, and then checks if that portion is equal to $ suffix .

Here are some examples of how to use these functions:

php
Copy code
$string1 = "Hello, world!";
$prefix = "Hello";
$suffix = "world!";

if (startsWith($string1, $prefix)) {
echo "String 1 starts with prefix\n";
}

if (endsWith($string1, $suffix)) {
echo "String 1 ends with suffix\n";
}
In this example, we define a string $string1, and two variables $prefix and $suffix. We then use the startsWith() function to check if $string1 starts with $prefix, and the endsWith() function to check if $string1 ends with $suffix. If either check is true, we output a message to the screen.
Post Answer