2010-02-25 70 views
3

我有一個字符串,例如「[{XYZ123}]這是一個測試」,需要解析出[{和}]之間的內容並將其轉儲到另一個字符串中。我假設一個正則表達式是爲了達到這個目的,但是因爲它不適合心靈不安,所以我沒有嘗試並且需要你的幫助。如何解析PHP中特定定界節的字符串?

在[{和}]之間拉出片段的最佳方式是什麼?在此先感謝您的幫助!

回答

2

正則表達式應該是(?=\[\{).*(?=\}\]),雖然我不知道php是否支持向前看。

+0

如果PHP不支持看aheads,你可以不用向前看符號'\ [\ {(。*?)\] \}' – Amarghosh 2010-02-25 05:04:51

+0

真的,我只是不知道有足夠的瞭解PHP告訴他如何提取反向引用。 – 2010-02-25 05:11:26

+0

我也不擅長php,但是如果我沒有記錯的話,'$ 1'語法可以在php中使用。 – Amarghosh 2010-02-25 05:43:11

4
<?php 
$str = "[{XYZ123}] This is a test"; 

if(preg_match('/\[{(.*?)}\]/',$str,$matches)) { 

$dump = $matches[1]; 

print "$dump"; // prints XYZ123 
} 

?> 
3
$str = "[{XYZ123}] This is a test"; 
$s = explode("}]",$str); 
foreach ($s as $k){ 
    if (strpos($k,"[{") !==FALSE){ 
    $t = explode("[{",$k); #or use a combi of strpos and substr() 
    print $t[1]; 
    } 
} 
+1

+1正則表達式被高估。 – 2010-02-25 05:02:52