PHP string ends with

There’s a hundred ways to do this, but here’s the one I came up with. It doesn’t use regex’s so it should be pretty quick.

function ends_with($str, $suffix) {
    return substr($str, -strlen($suffix)) == $suffix;

function starts_with($str, $prefix) {
    return substr($str, 0, strlen($prefix)) == $prefix;

For completeness, I added the corresponding starts_with function.

Posted in

One thought on “PHP string ends with

  1. The syntax of substr_compare() is as below:
    int substr_compare(string $main_str, string $str, int $offset [, int $length [, bool $case_insensitivity = false ]])
    substr_compare() compares main_str from position offset with str up to length characters.

Leave a Reply

Your email address will not be published. Required fields are marked *