PHP preg_match函数变量提取


PHP preg_match function variable extraction

假设我有这样一个字符串:

[$IMAGE[file_name|width|height]]

如何匹配并获得2个变量

$tag = "IMAGE"
$param = "file_name|width|height"

使用php preg_match函数?

$string = '[$IMAGE[file_name|width|height]]';
// Matches only uppercase & underscore in the first component
// Matches lowercase, underscore, pipe in second component
$pattern = '/'['$([A-Z_]+)'[([a-z_|]+)']']/';
preg_match($pattern, $string, $matches);
var_dump($matches);
array(3) {
  [0]=>
  string(32) "[$IMAGE[file_name|width|height]]"
  [1]=>
  string(5) "IMAGE"
  [2]=>
  string(22) "file_name|width|height"
}

不使用preg_match,但效果一样好。

$var = '[$IMAGE[file_name|width|height]]';
$p1 = explode('[',$var);
$tag = str_replace('$','',$p1[1]);
$param = str_replace(']','',$p1[2]);
echo $tag.'<br />';
echo $param;
<?php
$string = '[$IMAGE[file_name|width|height]]';
preg_match("/'[''$(.*)'[(.*)']']/",$string,$matches);
$tag = $matches[1];  
$param = $matches[2];
echo "TAG: " . $tag;
echo "<br />";
echo "PARAM: " . $param;
?>