2009-10-06 32 views
0

我有以下字符串將字符串分割以一定的方式

{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}..... 

如此這般上。

我需要通過以下方式分割字符串

1 => {}物品1家::::首頁{/物品1}

2 => {} ITEM2 :::: CONTACT_US聯繫我們{/ item2}

有沒有辦法?

回答

3

你可以做這樣的:

$text = "{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....){/item3}"; 
preg_match_all('/{item\d}.+?{\/item\d}/', $text, $results); 

var_dump($results)會產生:

Array 
(
    [0] => Array 
     (
      [0] => {item1}home::::Home{/item1} 
      [1] => {item2}contact_us::::Contact Us{/item2} 
      [2] => {item3}.....){/item3} 
     ) 

) 
2

使用preg_split()與正則表達式模式/{.*?}.*?{\/.*?}/

4
$input = '{item1}home::::Home{/item1}{item2}contact_us::::Contact Us{/item2}{item3}.....'; 
$regex = '/{(\w+)}.*{\/\1}/'; 
preg_match_all($regex, $input, $matches); 
print_r($matches[0]);