2010-01-06 120 views
0

我需要用PHP編寫的正則表達式這種模式的幫助:正則表達式來解析JSON

[[{"type":"media","view_mode":"small","fid":"1","attributes":{"width":0,"height":0,"src":"http://localhost/x.png"}}]] 

這是文本的一部分,我試圖用別的東西來代替這一點。

想使用preg_replace_all(),但無法弄清楚會是什麼模式。任何幫助讚賞。

回答

3

既然你說你需要確定正常的字符串中這些JSON串,你可以使用這個模式:

'/\[\[.*?]]/s' 

含義:

\[\[ # match two consecutive '['-s 
.*?  # reluctantly match any character 
]]  # match two consecutive ']'-s 

因爲s標誌,該.在正則表達式中也會匹配換行符。

演示:

$text = '<p>blahhah blahaa blahhah blahaablahhah blahaablahhah 
    blahaablahhah blahaablahhah blahaablahhah blahaablahhah 
    blahaablahhah blahaa [[{"type":"media","view_mode":"small", 
    "fid":"1","attributes":{"width":0,"height":0,"src": 
    "localhost/d7mw/sites/…;}}]] more blah more blah more blah 
    more blahmore blah more blahmore blah more blahmore blah 
    more blahmore blah more blahmore blah more blahmore blah 
    more blahmore blah more blahmore blah more blahmore blah 
    more blah</p>'; 
preg_match_all('/\[\[.*?]]/s', $text, $matches); 
print_r($matches); 

這將輸出:

Array 
(
    [0] => Array 
     (
      [0] => [[{"type":"media","view_mode":"small", 
    "fid":"1","attributes":{"width":0,"height":0,"src": 
    "localhost/d7mw/sites/…;}}]] 
     ) 

) 
+0

謝謝,看起來像有人明白這個問題。將試試:) – nutalk

+0

請注意,我只在你發佈這個JSON字符串在其他字符串內部的事實後才理解它。 –

+0

我在原始問題中寫過「這是一些文本的一部分」。謝謝,另外,當你在這是什麼最好的方式去除前面和結尾「[[」,以便我可以使用json_decode將其轉換爲一個php對象/數組。 – nutalk

2

這看起來像JSON編碼數據,您可以用json_decode乾淨地解析數據,然後再與json_encode合併。這裏不需要正則表達式。

+0

打我給它。 :) –

+0

不,儘管它的JSON我需要確定從表單傳遞的這種模式,然後將其替換。我需要先從其他文本中識別出來。 – nutalk

+0

好的,模式到底是什麼? –