How to check if a string ends in a word using str_ends_with

How to check if a string ends in given word str ends with

With every new major of version PHP comes a wealth of new functionality and improvements, and PHP version 8 is no exception to this rule. Version 8 brings a lot of great and long-requested functions compared to its predecessor PHP 7. Since version 8, PHP focused a lot of attention on bringing common and what seems more basic requests into the core language. These requests were those that programmers tend to perform a lot during different coding projects but didn't have a native function at the time. Such as finding a string contained in a substring or if a string ends in a given sub-string. Before PHP 8, it would have been the programmer who had to code a custom solution to these problems, but not anymore. In PHP 8, we now can use the str_ends_with function. But what does this function do and how does it work, we'll explore those questions and more in this guide.

What is the str_ends_with function?

The PHP function str_ends_with is a function that was added in PHP 8 and allows programmers to perform string manipulation to check if a string ends with a specified suffix (i.e. word, number, or letter). It provides a native and efficient way to check that given strings contain particular sub-strings. The function is case-sensitive, meaning it won't be matched to a string that contains the opposite case (i.e. searching uppercase versus a lowercase string). The function takes two parameters, the first is the "haystack", the string you're checking, and the second is the "needle" the string you're looking for. It will return a boolean (true or false) with true meaning it found it (the suffix), and otherwise, it will return false, it not finding anything.

str_ends_with(string $haystack, string $needle): bool

Let's look at a few examples of this function in action. First, let's see if our given string ends with the word "bar". Because our string ("Foo bar") does end in "bar", it returns true. In our next example, it returns false because "BAR" (in all capitals) isn't matched due to the case sensitivity of this function.

# Outputs true
str_ends_with('Foo bar', 'bar');

# Outputs false
str_ends_with('Foo bar', 'BAR');

Use PHP to check if a string ends with a number

Let's try some examples checking if strings end in numbers.

# Outputs true
str_ends_with('abc 123', '123');

Interestingly, even though the function requires you to pass a string as the second parameter "needle" if you pass a number, this number will be cast to the string before the function runs.

# Outputs true
str_ends_with('abc 123', 123);

Use PHP to check if the string ends with a slash

A common requirement in a project's codebase is to check if a string ends with a trailing slash. This is normally required when checking a URL. Now with PHP 8, this is extremely easy. Let's explore how in the PHP example below.

# Outputs true
str_ends_with('https://www.example.com/about/', '/');

String with == at the end

A quick way to check if a string ends with a double equal (maybe it's a base64 encoded string), is also quick and easy with PHP's str_ends_with function. In this example we're base64 encoding the string "foo bar" which results in the base64 string "Rm9vIGJhcg==" and then using str_ends_with to check if it ends with "==", which it does, therefore it returns true.

# Outputs true
str_ends_with(base64_encode('Foo bar'), '==');

str_ends_with function with arrays

Because the str_ends_with function requires you to pass two-stringed parameters, passing an array will result in a PHP fatal error. The following example will trigger a fatal error of "Fatal error: Uncaught TypeError: str_ends_with(): Argument #2 ($needle) must be of type string, array is given". Instead, you'll likely need to loop each item individually to check it ends in a given string, assuming the data inside are strings and not other nested arrays.

# Fatal error
str_ends_with('test', []);

str_ends_with PHP 7 polyfill

Because the str_ends_with function requires you to have PHP 8 or higher installed, it, unfortunately, isn't available in PHP 7 and any versions below that. Luckily there is a way around it with this PHP 7 polyfill. Here we are using the substr_compare function to check two against each other with an offset. The offset is there to ensure we're checking the end of the string, not the string as a whole. If the function returns true, we know that it ends in that string.

# PHP str_ends_with PHP 7 polyfill
if (substr_compare('Foo bar', 'bar', -strlen('bar')) === 0) {
 //...
}

Conclusion

The str_ends_with function in PHP is a quick and easy way to check if a string contains a particular substring. Thanks to PHP 8, we no longer have to create our own version of this function and instead can use a natively within PHP, meaning the code runs faster, due to it being a higher-level operation in the operating system, in this case, the C programming language.

  • The str_ends_with checks if a string ends in a particular sub-string
  • The str_ends_with function is case-sensitive
  • The str_ends_with function only accepts two parameters and raw numbers get cast to strings

Senior PHP developer. Author of Dev Lateral guides and tools. The complete place for PHP programmers. Available to hire to help you build or maintain your PHP application.

Looking for industry-leading PHP web development?

API development WordPress Hosting ★ and more 🐘

We use cookies to enhance your browsing experience, and analyse website traffic in accordance with our Privacy and Cookie Policy. Our cookies, including those provided by third parties, collect anonymous information about website usage and may be used for targeted advertising purposes. By clicking "Reject non-essential" you can opt out of non-essential cookies. By clicking "Accept all" you agree to the use of all cookies.


Reject non-essential Accept all