提取Word模式的关键字

时间:2016-02-05 14:28:26

标签: php regex

我有一个字符串。

hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}

我想从字符串中提取所有{$word}。我曾尝试使用str_replace,但它无效。

2 个答案:

答案 0 :(得分:1)

$string = 'hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}';
$variableRegexp = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
$repeatedVariableRegex = $variableRegexp . '(?:,\s*?\$' . $variableRegexp . ')*';
preg_match_all('/\{\$' . $repeatedVariableRegex . '\}/', $string, $matches);
var_dump($matches);

输出结果为:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(12) "{$USER_NAME}"
    [1] =>
    string(22) "{$USER1,$USER2,$USER3}"
  }
}

答案 1 :(得分:1)

preg_mach_all函数的简短解决方案:

$str = 'hi {$USER_NAME} THIS IS THE TEST MSG FOR {$USER1,$USER2,$USER3}';
preg_match_all('/\s*(\{\$[^\{\}]+\})+\s*/iue', $str, $matches);

echo "<pre>";
var_dump($matches[1]);

// the output:
array(2) {
  [0]=>
  string(12) "{$USER_NAME}"
  [1]=>
  string(22) "{$USER1,$USER2,$USER3}"
}

http://php.net/manual/ru/function.preg-match-all.php