2012-12-05 31 views
0

我想從包含括號的字符串(如{! !}。但是封裝字符串的開頭和結尾不應顯示空格。preg_match_all() - 在括號內使用文本,但不顯示空格

$string = "{! This should be in the output !} this should not be in the output {!show_in_output!} don't show {! show !}"; 
preg_match_all("/{!(.*)!}/Us", $string , $output); 

結果數組是這樣的:

Array 
(
    [0] => Array 
     (
      [0] => {! This should be in the output !} 
      [1] => {!show_in_output!} 
      [2] => {! show !} 
     ) 

    [1] => Array 
     (
      [0] => This should be in the output 
      [1] => show_in_output 
      [2] => show 
     ) 

) 

但它應該是這樣的:

Array 
(
    [0] => Array 
     (
... 
     ) 

    [1] => Array 
     (
      [0] => This should be in the output 
      [1] => show_in_output 
      [2] => show 
     ) 

) 

有沒有辦法用正則表達式修改來實現這一目標? 謝謝!

+0

爲什麼修改正則表達式時,你可以修剪後正則表達式? –

+0

是的,它可以被修改。 –

+0

當然,你可以修剪後的正則表達式,但我認爲這是不正確的方式來使用正則表達式。 – AndiPower

回答

1

/{!(.*)!}/中間的(.*)與您的{!!}之間的任意字符匹配。如果你不想在前後捕獲空格,你必須匹配空格,並且不要在你的組中包含空格,所以在你的情況下:/{!\s*(.*?)\s*!}/?表示要將.*最小匹配,以便它不包含第二個\s*要匹配的空白。

+1

謝謝!那很完美。 – AndiPower

+1

非常歡迎。請點擊灰色複選標記,以顯示您已接受答案。 –

+0

我只是試着完全理解它。爲什麼'。*'比'\ s *'更貪婪?因爲這個版本,我在'\ s *'更貪婪的地方工作:'/ {!\ s *?(。*)\ s *!}/U' – AndiPower

相關問題