2016-12-17 73 views
1

我有以下字符串:如何用左右分隔符匹配字符串?

$string = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 

我想提取每個子是之間{(||)}

我想:

$string = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 
preg_match('/([^{\(\|])(.*)([^\|\)}])/', $string, $matches); 

echo '<pre>'; 
print_r($matches); 
echo '</pre>'; 
die(); 

輸出:

Array 
(
    [0] => Teste 1|)}{(|Teste_2|)}{(|3 3 3 3 
    [1] => T 
    [2] => este 1|)}{(|Teste_2|)}{(|3 3 3 
    [3] => 3 
) 

所需的輸出:

Array 
(
    [0] => Teste 1 
    [1] => Teste_2 
    [2] => 3 3 3 
) 

我怎樣才能做到這一點的結果?
Thks!

+0

ÿ你可以在大多數情況下使用爆炸 – 2016-12-17 05:19:22

+0

'{\(\ |([^ \ |] *)\ | \)}' – bansi

回答

5

您的正則表達式語法不正確,您希望使用preg_match_all()來代替。

$str = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 
preg_match_all('/{\(\|([^|]*)\|\)}/', $str, $matches); 
print_r($matches[1]); 

輸出:

Array 
(
    [0] => Teste 1 
    [1] => Teste_2 
    [2] => 3 3 3 3 
) 
+1

讓我受到了5秒的傷害。這裏是[Demo](https://eval.in/699427) – bansi

+0

很多hwnd! – random425

2

這是使用str_replace

$string = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 
     $array = explode("|)}",str_replace("{(|","",$string)); 
     print_r(array_slice($array,0, -1)); 

不是最好的方法的另一種方式,但你可以記住。

+0

很多,Akshay! – random425

2

你可以嘗試下面的代碼

<?php 

$string = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 
preg_match('/{\(\|(.*?)\|\)}{\(\|(.*?)\|\)}{\(\|(.*?)\|\)}/', $string, $matches);  

preg_match_all('/{\(\|(.*?)\|\)}/', $string, $matches_all); 
echo '<pre>'; 
print_r($matches); 
print_r($matches_all); 
echo '</pre>'; 
+0

很多,亞輝江! – random425

1

你可以使用Lookaround匹配所需的輸出:

$string = '{(|Teste 1|)}{(|Teste_2|)}{(|3 3 3 3|)}'; 
preg_match_all('/(?<=\{\(\|).*?(?=\|\)\})/', $string, $matches); 
print_r($matches[0]); 

正則表達式演示:https://regex101.com/r/95wUo8/1

輸出:

Array 
(
    [0] => Teste 1 
    [1] => Teste_2 
    [2] => 3 3 3 
) 
+0

很多,易卜拉欣! – random425