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

检查是否$str1以某个字符串结尾的最佳方法是什么$arr1?答案真/假很好,虽然知道 $arr1 元素的数量作为答案(如果为真)会很好。

例子:

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

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

4

2 回答 2

4

从我的头顶上掉下来......

function check_end($str, $ends)
{
   foreach ($ends as $try) {
     if (substr($str, -1*strlen($try))===$try) return $try;
   }
   return false;
}
于 2012-04-24T11:18:51.677 回答
3

请参阅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
于 2012-04-24T11:40:05.263 回答