regex - PHP preg_split curly brackets


Keywords:php 


Question: 

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.


3 Answers: 

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.

 

In my opinion, the best function to call for your task is: preg_split(). It has a flag called PREG_SPLIT_DELIM_CAPTURE which allows you to retain your chosen delimiter in the output array. It is a very simple technique to follow and using negated character classes ([^}]*) is a great way to speed up your code. Further benefits of using preg_split() versus preg_match() include:

  • improved efficiency due to less capture groups
  • shorter pattern which is easier to read
  • no useless "fullstring" match in the output array

Code: (PHP Demo) (Pattern Demo)

$string = '<p>{titleInformation}<p>';
var_export(preg_split('/({[^}]*})/',$string,NULL,PREG_SPLIT_DELIM_CAPTURE));

Output:

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

If this answer doesn't work for all of your use cases, please edit your question to include the sample input strings and ping me -- I will update my answer.

 

With preg_split it can be done this way

preg_split('/[{}]+/', $myString);