2013-08-28 81 views
0

我想在php中搜索一個子字符串,以便它將在給定字符串的末尾。 例如 對字符串'abd def'如果我搜索def,它會在最後,所以返回true。但是,如果我搜索abd,它將返回false,因爲它不在最後。搜索子字符串,如果它在最後返回true

可能嗎?

+0

'是否有可能'?YES。 –

回答

0

假設全字:

​​

或使用正則表達式:

if (preg_match('/def$/', 'abd def')) { 
    ... 
} 
1

您可以使用preg_match此:

$str = 'abd def'; 
$result = (preg_match("/def$/", $str) === 1); 
var_dump($result); 
0

這個答案應該是充分堅固的,無論全文字或其他任何東西

$match = 'def'; 
$words = 'abd def'; 

$location = strrpos($words, $match); // Find the rightmost location of $match 
$matchlength = strlen($match);  // How long is $match 

/* If the rightmost location + the length of what's being matched 
* is equal to the length of what's being searched, 
* then it's at the end of the string 
*/ 
if ($location + $matchlength == strlen($words)) { 
    ... 
} 
0

請看strrchr()功能。像這樣嘗試

$word = 'abcdef'; 
$niddle = 'def'; 
if (strrchr($word, $niddle) == $niddle) { 
    echo 'true'; 
} else { 
    echo 'false'; 
} 
1

一種替代方法,它不需要按分隔符或正則表達式進行拆分。此測試是否最後x字符等於測試字符串,其中x等於測試字符串的長度:

$string = "abcdef"; 
$test = "def"; 

if(substr($string, -(strlen($test))) === $test) 
{ 
    /* logic here */ 
} 
相關問題