What's the most efficient test of whether a PHP string ends with another string?

后端 未结 13 663
时光说笑
时光说笑 2020-11-29 18:53

The standard PHP way to test whether a string $str ends with a substring $test is:

$endsWith = substr( $str, -strlen( $test ) ) ==          


        
相关标签:
13条回答
  • 2020-11-29 19:25

    Here’s a simple way to check whether one string ends with another, by giving strpos an offset right where the string should be found:

    function stringEndsWith($whole, $end)
    {
        return (strpos($whole, $end, strlen($whole) - strlen($end)) !== false);
    }
    

    Straightforward, and I think this’ll work in PHP 4.

    0 讨论(0)
  • 2020-11-29 19:25

    In PHP 8:

    str_ends_with('haystack', 'stack'); // true
    str_ends_with('haystack', 'K'); // false
    

    and also:

    str_starts_with('haystack', 'hay'); // true
    

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

    0 讨论(0)
  • 2020-11-29 19:29

    I'm thinking the reverse functions like strrchr() would help you match the end of the string the fastest.

    0 讨论(0)
  • 2020-11-29 19:30

    What Assaf said is correct. There is a built in function in PHP to do exactly that.

    substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;
    

    If $test is longer than $str PHP will give a warning, so you need to check for that first.

    function endswith($string, $test) {
        $strlen = strlen($string);
        $testlen = strlen($test);
        if ($testlen > $strlen) return false;
        return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
    }
    
    0 讨论(0)
  • 2020-11-29 19:32

    I hope that the below answer may be efficient and also simple:

    $content = "The main string to search";
    $search = "search";
    //For compare the begining string with case insensitive. 
    if(stripos($content, $search) === 0) echo 'Yes';
    else echo 'No';
    
    //For compare the begining string with case sensitive. 
    if(strpos($content, $search) === 0) echo 'Yes';
    else echo 'No';
    
    //For compare the ending string with case insensitive. 
    if(stripos(strrev($content), strrev($search)) === 0) echo 'Yes';
    else echo 'No';
    
    //For compare the ending string with case sensitive. 
    if(strpos(strrev($content), strrev($search)) === 0) echo 'Yes';
    else echo 'No';
    
    0 讨论(0)
  • 2020-11-29 19:34

    Don't know if this is fast or not but for a single character test, these work, too:

    (array_pop(str_split($string)) === $test) ? true : false;
    ($string[strlen($string)-1] === $test) ? true : false;
    (strrev($string)[0] === $test) ? true : false;
    
    0 讨论(0)
提交回复
热议问题