4
$arr1 = array ("llo" "world", "ef", "gh" );

What's the best way to check if $str1 ends with some string from $arr1? The answer true/false is great, although knowing the number of $arr1 element as an answer (if true) would be great.

Example:

$pos= check_end("world hello");//$pos=0; because ends with llo
$pos= check_end("hello world");//$pos=1; because ends with world.

Is there any better/faster/special way than just comparing in for-statement all elements of $arr1 with the end of $str1?

Haradzieniec
  • 8,592
  • 29
  • 109
  • 204
  • 1
    possible duplicate of [PHP startsWith() and endsWith() functions](http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions) – Felix Kling Apr 24 '12 at 11:14
  • Will no value of `$arr1` be an ending substring of another value of `$arr1`? Because if s/t like `$arr1 = array('llo', 'lo', 'hi')` is possible, you need to further clarify which element's number should be returned in case of multiple matches. – Jürgen Thelen Apr 24 '12 at 11:34
  • Thank you. Both of 'llo' or 'lo' as an answer is fine. (No one of $arr1 elements is actually a substring of one another, they are predefined). But, thanks for this notice. – Haradzieniec Apr 24 '12 at 12:10

2 Answers2

4

Off the top of my head.....

function check_end($str, $ends)
{
   foreach ($ends as $try) {
     if (substr($str, -1*strlen($try))===$try) return $try;
   }
   return false;
}
symcbean
  • 46,644
  • 6
  • 56
  • 89
3

See startsWith() and endsWith() functions in PHP for endsWith

Usage

$array = array ("llo",  "world", "ef", "gh" );
$check = array("world hello","hello world");

echo "<pre>" ;

foreach ($check as $str)
{
    foreach($array as $key => $value)
    {
        if(endsWith($str,$value))
        {
            echo $str , " pos = " , $key , PHP_EOL;
        }
    }

}


function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    $start  = $length * -1; //negative
    return (substr($haystack, $start) === $needle);
}

Output

world hello = 0
hello world = 1
Community
  • 1
  • 1
Baba
  • 92,047
  • 28
  • 163
  • 215