2012-04-24 82 views
2
$arr1 = array ("llo" "world", "ef", "gh"); 

什麼是最好的方法來檢查$str1$arr1的字符串結尾? 雖然知道$ arr1元素的數目作爲答案(如果爲真)會很好,但答案true/false很好。php:檢查字符串是否以數組元素結尾的最佳方法?

例子:

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

有沒有更好的/快/特殊不僅僅是比較在語句的$arr1所有元素與$str1末呢?

+1

可能重複startsWith()和endsWi th()函數](http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions) – 2012-04-24 11:14:03

+0

'$ arr1'是'$ arr1'的另一個值的結束子字符串嗎?因爲如果s/t像'$ arr1 = array('llo','lo','hi')'是可能的,你需要進一步澄清在多個匹配情況下應該返回哪個元素的數字。 – 2012-04-24 11:34:54

+0

謝謝。 'llo'或'lo'作爲答案都很好。 ($ arr1元素中沒有一個實際上是另一個的子串,它們是預定義的)。但是,感謝您的通知。 – Haradzieniec 2012-04-24 12:10:50

回答

3

關閉我的頭頂.....

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

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

輸出中看到startsWith() and endsWith() functions in PHP

world hello = 0 
hello world = 1 
[PHP的
相關問題