2011-01-09 68 views
9

修剪子要處理一組字符串,並且每個字符串年底修剪一些結束「myEnding」 如果存在PHP:最好的方法從字符串

最簡單的方法是什麼? 我知道一切都可能與正則表達式,但因此似乎是一個簡單的任務,我不知道是否存在一個更簡單的工具。

感謝

吉迪

+0

你可能會發現[`s($ str) - > replaceSuffix('myEnd ')(https://github.com/delight-im/PHP-Str/blob/ea3e40132e9d4ce27da337dae6286f2478b15f56/src/Str.php#L442)有幫助,在[這個獨立的庫]中找到(https:// github的.com /喜悅-IM/PHP-STR)。 – caw 2016-07-28 04:11:34

回答

8

IMA去在這一個的preg_replace。

$output = preg_replace('/myEnding$/s', '', $input); 
+0

坦克的寶貴答案,即使我問了非正則表達式解決方案 – shealtiel 2011-01-09 03:10:18

+1

你問最簡單的方法來做到這一點。在這種情況下,正則表達式是最簡單的方法。 – dqhendricks 2011-01-09 03:11:44

5

試試這個:

$s = "foobarmyEnding"; 
$toRemove = "myEnding"; 

$len = strlen($toRemove); 
if (strcmp(substr($s, -$len, $len), $toRemove) === 0) 
{ 
    $s = substr($s, 0, -$len); 
} 

ideone

相關問題