2011-07-30 38 views
0

我有以下幾點:將內容從括號中刪除的最佳方式是什麼?(你好)?

(你好) (hello123) (hello123 $ pecialChars &#@)

我需要一種方法每次都得到括號之間的內容。什麼是做這件事的好方法?

+0

你有什麼試過? :)請記住'('和')'在正則表達式中是特殊的,因此需要加以保護。 – 2011-07-30 06:27:41

+0

我試過 - > $ items = preg_match_all('#\ d +#',$ string,$ matches); foreach($作爲$ items匹配){echo $ items}但該正則表達式僅提取整數。我的正則表達式很糟糕,所以我卡住了。 – Fran

回答

4

那麼因爲每個()中都沒有空格,所以下列模式應該可以工作\(([^ ]+)\)/(匹配一個或多個不是空格的東西,並且在圓括號之間,它們被轉義爲文字字符):

$data = "(hello) (hello123) (hello123$pecialChars&#@)"; 
preg_match_all('/\(([^ ]+)\)/', $data, $arr, PREG_PATTERN_ORDER); 

// print_r($arr) gives: 
Array 
(
    [0] => Array 
     (
      [0] => (hello) 
      [1] => (hello123) 
      [2] => (hello123$pecialChars&#@) 
     ) 

    [1] => Array 
     (
      [0] => hello 
      [1] => hello123 
      [2] => hello123$pecialChars&#@ 
     ) 

) 

編輯:如前所述,圖案\(([^)]+)\),或match an open parenthesis followed by one or more characters that are not a close parenthesis and are followed by a close parenthesis,(取決於你可能在你的數據一個右括號,或者你可能有空格)可能會更好。

+1

我會考慮'[^]] +'自己,但是... – 2011-07-30 06:52:16

+0

@pst我喜歡它!看起來更好,更有意義,不會將其限制爲非空格,而且正是他想要的。 –

相關問題