Search code examples
phpregexsplitpreg-split

PHP preg_split curly brackets


Who can help me out? I have a string like this:

$string = '<p>{titleInformation}<p>';

I want to split this string so that I get the following array:

array ( 
  0 => '<p>',
  1 => '{titleInformation}', 
  2 => '<p>',
)

I'm new to regular expressions and I tried multiple patterns with the preg_match_all() function but I cant get the correct one. Also looked at this question PHP preg_split if not inside curly brackets, but I don't have spaces in my string.

Thank you in advance.


Solution

  • Use preg_match() with capture groups. You need to escape the curly braces because they have special meaning in regular expressions.

    preg_match('/(.*?)(\\{[^}]*\\})(.*)/', $string, $match);
    var_dump($match);
    

    Result:

    array(4) {
      [0]=>
      string(24) "<p>{titleInformation}<p>"
      [1]=>
      string(3) "<p>"
      [2]=>
      string(18) "{titleInformation}"
      [3]=>
      string(3) "<p>"
    }
    

    $match[0] contains the match for the entire regexp, elements 1-3 contain the parts that you want.