PHP:检查字符串是否以数组中的元素结尾的最佳方法


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

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

检查$str1是否以$arr1中的一些字符串结尾的最佳方法是什么?答案真/假很棒,尽管知道 $arr 1 元素的数量作为答案(如果为真)会很棒。

例:

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

有没有比在 for 语句中比较$arr1的所有元素与$str1末尾更好/更快/特殊的方法?

在我的头顶上.....

function check_end($str, $ends)
{
   foreach ($ends as $try) {
     if (substr($str, -1*strlen($try))===$try) return $try;
   }
   return false;
}

请参阅 PHP 中的 startsWith() 和 endsWith() 函数以了解endsWith

用法

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

输出

world hello = 0
hello world = 1

很确定这会起作用。 定义你自己的"any"函数,它接受一个数组,如果它的任何值计算结果为 true,则返回 true,然后使用 php 的 array_map 函数执行等效的列表推导来构造一个数组以传递给它。 这可以组合成一个函数,但你可能会发现"any"函数本身在其他地方很有用。

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