views:

140

answers:

4

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"/]

A: 
$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);
ghostdog74
I'm a novice at PHP and I'm trying to get better and this just made my night. Thank you so much ghostdog74!
Hunter Satterwhite
If this solved your problem you should award an answer by clicking the check mark next to the question so that others interested in the answer can find what worked for you.
Austin Fitzpatrick
A: 

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%
        )

)
Max Shawabkeh
+1  A: 

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
)
Alix Axel
A: 

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']));
Charles