preg_match a "shortcode" to create an array with semantic array keys

How would I preg_match the following piece of "shortcode" so that video and align are array keys and their values are what is with in the quotes? [video="123456" align="left"/]

Answers


$string='[video="123456" align="left"/]';
$string= preg_replace("/\/|\[|\]/","",$string);
$s = explode(" ",$string);
foreach ($s as $item){
    list( $tag, $value) = explode("=",$item);
    $array[$tag]=$value;
}
print_r($array);

Here is another approach using array_combine():

$str = '[video="123456" align="left"/][video="123457" align="right"/]';

preg_match_all('~\[video="(\d+?)" align="(.+?)"/\]~', $str, $matches);

$arr = array_combine($matches[1], $matches[2]);

print_r() output of $arr:

Array
(
    [123456] => left
    [123457] => right
)

Alternate solution with named parameters:

$str = '[video="123456" align="left"/][video="123457" align="right"/]';

$matches = array();
preg_match_all('/\[video="(?P<video>\d+?)"\salign="(?P<align>\w+?)"\/\]/', $str, $matches);

for ($i = 0; $i < count($matches[0]); ++ $i)
   print "Video: ".$matches['video'][$i]." Align: ".$matches['align'][$i]."\n";

You could also reuse the previous array_combine solution given by Alix:

print_r(array_combine($matches['video'], $matches['align']));

I don't think there's any (simple) way to do it using a single regex, but this will work in a fairly general way, picking out the tags and parsing them:

$s = 'abc[video="123456" align="left"/]abc[audio="123456" volume="50%"/]abc';

preg_match_all('~\[([^\[\]]+)/\]~is', $s, $bracketed);
$bracketed = $bracketed[1];

$tags = array();
foreach ($bracketed as $values) {
  preg_match_all('~(\w+)\s*=\s*"([^"]+)"~is', $values, $pairs);
  $dict = array();
  for ($i = 0; $i < count($pairs[0]); $i++) {
    $dict[$pairs[1][$i]] = $pairs[2][$i];
  }

  array_push($tags, $dict);
}

//-----------------    

echo '<pre>';
print_r($tags);
echo '</pre>';

Output:

Array
(
    [0] => Array
        (
            [video] => 123456
            [align] => left
        )

    [1] => Array
        (
            [audio] => 123456
            [volume] => 50%
        )

)

Need Your Help

Validating the phone number with a regex ruby

ruby-on-rails ruby-on-rails-3.1

I am trying to validate if the phone number is a digit or not :-

How to generate a range of random numbers in python without repetition

python random seed

I would like to generate random numbers in the range (0..."MAX"). I would like to make a loop such that every time going through the loop a new unique random number is generated (should not repeat)...