2010-04-28 33 views
1

我有一個字符串,它是刪除Word +通配符數量從字符串

$str = "testingSUB1"; 

如何從字符串剔除SUB*?我假設使用preg_replace,但我並不擅長用正則表達式匹配我想要的。

有誰知道我該怎麼做?

謝謝

回答

3

就是這樣。

$str = preg_replace("#SUB[0-9]+#", "", $str); 

# s是分隔符;它們可以是不出現在模式中的任何非字母數字/空白/反斜槓字符。 [0-9]意味着任何數字(在某些語言中也可以使用\d,但我通常不會打擾),而+意味着前面的一個或多個,因此如果將+取出,它只會替換第一個數字

+0

+1 - 可是爲什麼#,而不是/? – Ben 2010-04-28 01:43:22

+0

我養成了使用#的習慣,因爲它很少出現在模式中,而/總是顯示出來(例如在URL或Linux路徑中)。/will will working – 2010-04-28 01:52:17

+1

儘可能使用'''替代''''''也意味着前面的任何數字都是不正確的,這意味着一個或多個' – gameover 2010-04-28 03:44:24

2

這應做到:

$word = 'SUB'; 
$string = 'testingSUB1'; 

echo preg_replace('~^(.*?)(' . preg_quote($word, '~') . '\d+)(.*?)$~', '$1$2', $string); 

編輯 - 這是更好的:

echo preg_replace('~' . preg_quote($word, '~') . '\d+~', '', $string); 
+0

+1 for preg_quote。不知道這個功能。 – mpen 2010-04-28 01:34:11