修剪子要處理一組字符串,並且每個字符串年底修剪一些結束「myEnding」 如果存在。PHP:最好的方法從字符串
最簡單的方法是什麼? 我知道一切都可能與正則表達式,但因此似乎是一個簡單的任務,我不知道是否存在一個更簡單的工具。
感謝
吉迪
修剪子要處理一組字符串,並且每個字符串年底修剪一些結束「myEnding」 如果存在。PHP:最好的方法從字符串
最簡單的方法是什麼? 我知道一切都可能與正則表達式,但因此似乎是一個簡單的任務,我不知道是否存在一個更簡單的工具。
感謝
吉迪
IMA去在這一個的preg_replace。
$output = preg_replace('/myEnding$/s', '', $input);
坦克的寶貴答案,即使我問了非正則表達式解決方案 – shealtiel 2011-01-09 03:10:18
你問最簡單的方法來做到這一點。在這種情況下,正則表達式是最簡單的方法。 – dqhendricks 2011-01-09 03:11:44
試試這個:
$s = "foobarmyEnding";
$toRemove = "myEnding";
$len = strlen($toRemove);
if (strcmp(substr($s, -$len, $len), $toRemove) === 0)
{
$s = substr($s, 0, -$len);
}
rtrim
http://php.net/manual/en/function.rtrim.php
$str = "foobarmyEnding";
$str = rtrim($str, 'myEnding');
// str == "foobar"
LTRIM相同處理的字符串的開頭http://php.net/manual/en/function.ltrim.php
你也可以使用str_replace函數與一個空字符串,但它的速度較慢更換搜索詞然後rtrim/ltrim如果你需要修改一個字符串的開始或結尾
你可能會發現[`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