开发者

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


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
)


$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);


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

)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜