2011-04-12 128 views
2

我有以下字符串:PHP正則表達式preg_match_all字符串

關鍵字|標題| HTTP://example.com/

我想用PHP函數

preg_match_all ($anchor, $key, $matches, PREG_SET_ORDER)) 

當前

$anchor='/([\w\W]*?)\|([\w\W]*)/'; 

我得到$ matches數組:

Array 
(
    [0] => Array 
     (
      [0] => keyword|title|http://example.com/ 
      [1] => keyword 
      [2] => title|http://example.com/ 
     ) 

) 

我想獲得

matches[1]=keyword 
matches[2]=title 
matches[3]=http://example.com 

我會如何修改$錨實現這一目標?

+0

你只需要在你的正則表達式中增加一個'\ |([\ w \ W] *?)''。 – mario 2011-04-12 21:12:33

+0

謝謝,這工作。最終表達式:$ anchor ='/([\ w \ W] *?)\ |([\ w \ W] *?)\ |([\ w \ W] *)/'; – IberoMedia 2011-04-12 21:52:14

回答

1

如果你想使用正則表達式,以避免手動循環來保持,那麼我建議這在使用[\w\W]*語法和可讀性:

$anchor = '/([^|]*) \| ([^|]*) \| ([^\s|]+)/x'; 

這是有明確否定的字符類稍有更穩健。 (我假設在這裏既沒有標題也沒有url可以包含|)。

+0

嘿馬里奧,謝謝你,這工作。我對正則表達式一無所知。他們對我來說看起來像是胡言亂語。我在哪裏可以找到這些表達式的規則和機制?謝謝 – IberoMedia 2011-04-14 21:49:22

+0

是的。他們是一種自己的編程語言。習慣它們需要時間。 http://regular-expressions.info/提供了一個很容易理解的介紹。下面是一些有時可以幫助構建正則表達式的工具:http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world – mario 2011-04-14 21:59:57

6

最簡單的方法是使用explode(),而不是正則表達式:

$parts = explode('|', $str); 

部分的假設沒有一個可以包含|。但是,如果他們可以,正則表達式也不會幫助你。

+0

絕對如此。只是爲了它...繼承人正則表達式會工作:'/([^ |] +)/' – 2011-04-12 21:08:10

+0

加里,這是匹配,如果我使用這個正則表達式:

Array ( [0] => Array ( [0] => keyword [1] => keyword ) [1] => Array ( [0] => title [1] => title ) [2] => Array ( [0] => http://example.com/ [1] => http://example.com/ ) ) 
IberoMedia 2011-04-12 21:42:02