Assuming that I have a string like this:
[$IMAGE[file_name|width|height]]
How can I match and obtain 2 variables
$tag = "IMAGE"
$param = "file_name|width|height"
Using a php preg_match function?
$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"
}
Doesn't use preg_match, but works just as well.
$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() to limit to 2 components $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;
?>
([^\]]*) to avoid greedy results.