2010-09-17 143 views
1
$variable = 'of course it is unnecessary [http://google.com], 
but it is simple["very simple"], and this simple question clearly 
needs a simple, understandable answer [(where is it?)] in plain English' 

每次更改此變量的值。在字符串內搜索

我想要做的是從[...]獲取文本。所以,如果有[(google)],那麼匹配應該是(google)

我在尋找一個解決方案,它可以做這些動作:

  1. 獲得的所有比賽[...],寫入$all
  2. 只得到第一比賽,寫入$first
  3. 只得到最後比賽,寫入$last
  4. 刪除[...]自變量(擦除)的所有比賽
  5. 僅刪除第一場比賽
  6. 只刪除最後一場比賽

嘗試不同的正則表達式這一點,像/[\(.*?\)]/,但結果不是人們所預料的。

+0

試試這個'/ \\ [([^ \\] *)\\] /' – jcubic 2010-09-17 10:37:37

+0

@jcubic,有什麼區別? – James 2010-09-17 10:51:42

+0

括號是特殊的正則表達式字符,如果你想匹配括號,你必須轉義它。 – jcubic 2010-09-17 11:19:32

回答

2

這應做到:

$variable = 'of course it is unnecessary [http://google.com], 
but it is simple["very simple"], and this simple question clearly 
needs a simple, understandable answer [(where is it?)] in plain English'; 

preg_match_all("/(\[(.*?)\])/", $variable, $matches); 

$first = reset($matches[2]); 
$last = end($matches[2]); 
$all = $matches[2]; 

# To remove all matches 
foreach($matches[1] as $key => $value) { 
    $variable = str_replace($value, '', $variable); 
} 

# To remove first match 
$variable = str_replace($first, '', $variable); 

# To remove last match 
$variable = str_replace($last, '', $variable); 

請注意,如果您使用str_replace函數來代替標籤,標籤的所有類似OCCURENCES將如果這樣的存在,而不只是第取出。

+0

應該有一種方法來刪除所有,第一次或只有最後一次匹配 – James 2010-09-17 10:38:08

+0

** $ first **是** [(它在哪裏?)] **它應該是**(它在哪裏?)** (刪除[和]) – James 2010-09-17 10:40:58

+0

@快樂,這是固定的,有錯誤的關鍵。 – 2010-09-17 10:44:29