从另一个以特殊字符开头和结尾的字符串中提取字符串


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

假设我有一个字符串

这{是}一个新的{test}{字符串}从我。

我的意图是在数组或列表中获得由{}包围的所有字符串。所以我想得到:

{is} {test} {string}

子字符串在这里不起作用。也许'regex'是解决方案,但我只是不能让它为我工作。有人能帮忙吗?

您希望使用正则表达式。在本例中,您希望使用以下正则表达式:

/'{[^}]*'}/

这是什么意思?

  • / = regex起始
  • '{ =匹配{
  • [^}] =匹配除}之外的任何字符…
  • * =…1到无限次
  • '} =匹配}
  • / = end of regex

你可以这样使用:

$re = "/'{[^}]*}/";
$str = "This {is} a new {test} {string} from me."; 
preg_match_all($re, $str, $matches);
print_r($matches[0]);

,其中$matches[0]是一个匹配数组。这将输出:

阵列([0]=>{是}[1]=>{测试}[2]=>{字符串})