正则表达式以获取双花括号“{{}}”内的值

时间:2013-10-11 11:21:18

标签: php regex

PHP中的正则表达式,用于在数组中使用“{{}}”获取内部引用的文本。

例如:

$str = "This is sample content with a dynamic value {{value1}} and also have more dynamic values {{value2}}, {{value3}}";

需要输出如下面的数组

array(value1,value2,value3);

3 个答案:

答案 0 :(得分:8)

这将有效:

$str = "This is sample content with a dynamic value {{value1}} and also have more dynamic values {{value2}}, {{ value3 }}";
if (preg_match_all("~\{\{\s*(.*?)\s*\}\}~", $str, $arr))
   var_dump($arr[1]);

<强>输出:

array(3) {
  [0]=>
  string(6) "value1"
  [1]=>
  string(6) "value2"
  [2]=>
  string(6) "value3"
}

答案 1 :(得分:1)

使用此:

preg_match_all('~\{\{(.*?)\}\}~', $string, $matches);
var_dump($matches[1]);

输出:

array(3) {
  [0] =>
  string(6) "value1"
  [1] =>
  string(6) "value2"
  [2] =>
  string(6) "value3"
}

答案 2 :(得分:0)

preg_match_all('/\{\{([^}]+)\}\}/', $str, $matches);
$array = $matches[1];