【发布时间】:2011-12-13 14:24:09
【问题描述】:
假设我有这样的字符串:
[$IMAGE[file_name|width|height]]
如何匹配并获取2个变量
$tag = "IMAGE"
$param = "file_name|width|height"
使用 php preg_match 函数?
【问题讨论】:
标签: php regex tags pattern-matching preg-match
假设我有这样的字符串:
[$IMAGE[file_name|width|height]]
如何匹配并获取2个变量
$tag = "IMAGE"
$param = "file_name|width|height"
使用 php preg_match 函数?
【问题讨论】:
标签: php regex tags pattern-matching 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;
【讨论】:
explode() 的第三个参数来限制为 2 个组件 $p1 = explode('[', $var, 2);
<?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;
?>
【讨论】:
([^\]]*) 来避免贪婪的结果。