user3813280 user3813280 - 1 year ago 42
PHP Question

Extract strings from another string beginning and ending with a special char

let's say I have a string like

This {is} a new {test} {string} from me.

My intention is to get all the strings surrounded by the
in a array, or a list.
So I want to get:

{is} {test} {string}

Substring won't work here. Probably 'regex' is the solution, but I just can't get it to work for me. Can someone help?

Ben Ben
Answer Source

You want to use a regular expression. In this case, you want to use the following regular expression:


What does this mean?

  • / = start of regex
  • \{ = match the character {
  • [^}] = match any character except }...
  • * = ... 1 to unlimited times
  • \} = match the character }
  • / = end of regex

You can use this like so:

$re = "/\{[^}]*}/";
$str = "This {is} a new {test} {string} from me."; 

preg_match_all($re, $str, $matches);


where $matches[0] is an array of matches. This will output:

Array ( [0] => {is} [1] => {test} [2] => {string} )