1

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?

3 Answers 3

6
$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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 as it will scale for multiple instances in the same string
1

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;

3 Comments

+1 for workable string operations. Suggest using the 3rd param to explode() to limit to 2 components $p1 = explode('[', $var, 2);
thanks @Michael - I tried adding that third param and the var_dump gave me a string[0] of "", and string[1] of the full string?
@Michael ah - got it, needs to be 3 not 2, as the first item in the array is an empty string
0
<?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;
?>

1 Comment

I would use ([^\]]*) to avoid greedy results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.