Regex to match substring within found brackets?

Hi,

I’m trying to extract a particular value from a bbcode-like tag, but can only seem to get part of it right. Let’s say I have these tags in a string of HTML…


[imageswap skin="some-skin-name"]
[imageswap skin="some-skin-name" w="140" other="params" are="unimportant"]
[imageswap w="140" other="params" are="unimportant" skin="some-skin-name"]

I’m after the value of the “skin” attribute of each of these tags, which might consist of alphanumerics and hyphens. The location of the skin attribute (within the imageswap tag) is arbitrary and I have no way to know if it will be the first argument, second argument, last argument, etc… Finally, I can’t be absolutely positive that any of these tags’ attributes will use single-quotes, double-quotes, or no quotes at all.

Here’s my pattern so far…which (headdesk) took me 2 hours to cobble together.

$pattern = '/\\[imageswap skin="(.*?)"\\]/';

Your regexy ninja-ness will be greatly appreciated, thanks!

Okay so -

1: Only inside [imageswap] BBCode.
2: skin attribute
3: quotes optional
4: defined as alphanum + hyphen

Attempt #2: (untested)


~\\[imageswap .*?skin=['"]?([a-z0-9-]*)['"]?.*?\\]~i

EDIT: \w includes _ so replaced with alphanum ranges.

Hi,
Try the regexp pattern from this example:

<?php
$tag = '[imageswap w="140" other="params" are="unimportant" skin="some-skin-name"]';
if(preg_match('/\\[imageswap(.+?)skin=["\\'](.*?)["\\']/i', $tag, $mc)) {
  $skin = $mc[2];
  echo $skin;                // some-skin-name
}
?>

That example doesnt fulfill requirement 3 or 4, also captures unnecessary subpattern.

Thank you both for the assist!

StarLion, your solution worked without a single tweak and I’m most grateful! As an interim workaround, I wrote a whopping 13 lines of completely-unmaintainable, string-inspecting bogus-ness to finally arrive at the skin names. It worked to keep the project moving along in the moment, but your pattern brought it down to a highly-maintainable, self-explanatory 4 lines. Thanks a mil! :smiley: