$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.
有没有更好/更快/特殊的方式,只需比较$arr1
的所有元素的for-statement和$str1
的结尾?
答案 0 :(得分:4)
脱离我的头顶.....
function check_end($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
答案 1 :(得分:3)
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