Haradzieniec
Haradzieniec

Reputation: 9338

php: the best way to check if string ends with an element from array?

$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?

Upvotes: 4

Views: 3704

Answers (3)

tklodd
tklodd

Reputation: 1079

Pretty sure this will work. Define your own "any" function, which takes an array and returns true if any of its values evaluate to true, and then use php's array_map function to do the equivalent of list-comprehension to construct an array to pass to it. This could instead be combined into one function, but you'll probably find the "any" function useful elsewhere in its own right anyway.

if (!function_exists('any')) {
    function any(array $array):bool {
        return boolval(array_filter($array));
    }
}

function check_end (string $needle, array $haystack):bool {
    return any(
        array_map(
            function (string $end) use ($needle):bool {
                return str_ends_with($needle, $end);
            },
            $haystack,
        )
    );
}

Upvotes: 0

Baba
Baba

Reputation: 95161

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

Upvotes: 3

symcbean
symcbean

Reputation: 48387

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;
}

Upvotes: 4

Related Questions