Search code examples
phpregexpreg-match

How to match strings with left and right delimiters?


I have the following string:

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

I want to extract every substring that is between {(| and |)}.

I'm trying:

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

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

Outputs:

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

Desired output:

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

How can I accomplish this result?
Thks!


Solution

  • Your regular expression syntax is incorrect and you want to use preg_match_all() instead.

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

    Output:

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