2012-01-05 113 views
4

echo $string可以給出任何文字。僅替換字符串的末尾

如何刪除字"blank",只有當它是的最後一個字

因此,如果我們有像"Steve Blank is here"這樣的句子 - 不應該刪除任何內容,否則如果句子是"his name is Granblank",那麼應刪除"Blank"單詞。

回答

12

你可以很容易地使用正則表達式。 \b確保只有它是一個單獨的詞時纔會被刪除。

$str = preg_replace('/\bblank$/', '', $str); 
+0

這個代碼將取代「空白」無處不在,應該只需更換,如果它是字符串中的最後一次出現。 – Jasper 2012-01-05 23:54:33

+3

錯誤。這就是'$'的用途。 – EboMike 2012-01-06 00:01:42

+3

@Steve你試過這段代碼嗎?它適用於您建議的用例。僅當字符串末尾爲空時,$表示匹配。雖然在你的具體用例中,正則表達式應該是/ blank $ /,因爲你不關心字邊界。 – Owen 2012-01-06 00:04:12

1

嘗試以下:

$str=trim($str); 
    $strlength=strlen($str); 

    if(strcasecmp(substr($str,($strlength-5),$strlength),'blank')==0) 
     echo $str=substr($str,0,($strlength-5)) 

不要使用preg_match unlesss它不是必需的,PHP本身建議使用字符串函數在正則表達式功能,當比賽很簡單。從preg_matc h手冊頁

+0

我認爲有點過分複雜。 – buley 2012-01-05 23:53:13

+1

然後製作正則表達式和單獨的函數並不複雜。您可以通過分步實現更簡單。我們只是使用內置的finctions。 – 2012-01-06 00:06:52

+0

是的,但考慮這個解決方案的可維護性,當與接受的答案比較... – cmbuckley 2012-01-06 10:29:37

-2

ThiefMaster是相當正確的。不涉及結束行$正則表達式字符的技術將使用rtrim

$trimmed = rtrim($str, "blank"); 
var_dump($trimmed); 

^這就是如果你想刪除字符串的最後一個字符。如果你想刪除的最後一個字:

$trimmed = rtrim($str, "\sblank"); 
var_dump($trimmed); 
+0

將不會替換字符串中的「空白」,如字符串末尾的「Granblank」 – Jasper 2012-01-05 23:56:11

+0

啊,他自己的定義說「只有當它是$字符串的最後一個單詞「不」,只有當它是字符串的最後一個字符時。「編輯。如果是這種情況,那麼'rtrim'更具吸引力。 – buley 2012-01-06 00:01:21

+0

這就是你要求的,你說如果空白是字符串的最後一個WORD,而不是「如果字符串以'空白'結尾。」但是,如果它是「Gran.blank」,它將會失敗。 – EboMike 2012-01-06 00:01:31

3

上Teez的回答變化:

/** 
* A slightly more readable, non-regex solution. 
*/ 
function remove_if_trailing($haystack, $needle) 
{ 
    // The length of the needle as a negative number is where it would appear in the haystack 
    $needle_position = strlen($needle) * -1; 

    // If the last N letters match $needle 
    if (substr($haystack, $needle_position) == $needle) { 
     // Then remove the last N letters from the string 
     $haystack = substr($haystack, 0, $needle_position); 
    } 

    return $haystack; 
} 

echo remove_if_trailing("Steve Blank is here", 'blank'); // OUTPUTS: Steve blank is here 
echo remove_if_trailing("his name is Granblank", 'blank'); // OUTPUTS: his name is Gran