function get_pattern($text) {
$pattern = get_shortcode_regex();
preg_match_all("/$pattern/s", $text, $c);
return $c;
}
function parse_atts($content) {
$content = preg_match_all('/([^ ]*)=(\'([^\']*)\'|\"([^\"]*)\"|([^ ]*))/', trim($content), $c);
list($dummy, $keys, $values) = array_values($c);
$c = array();
foreach ($keys as $key => $value) {
$value = trim($values[ $key ], "\"'");
$type = is_numeric($value) ? 'int' : 'string';
$type = in_array(strtolower($value), array('true', 'false')) ? 'bool' : $type;
switch ($type) {
case 'int': $value = (int) $value; break;
case 'bool': $value = strtolower($value) == 'true'; break;
}
$c[ $keys[ $key ] ] = $value;
}
return $c;
}
function the_shortcodes(&$output, $text, $child = false) {
$patts = get_pattern($text);
$t = array_filter(get_pattern($text));
if (! empty($t)) {
list($d, $d, $parents, $atts, $d, $contents) = $patts;
$out2 = array();
$n = 0;
foreach($parents as $k=>$parent) {
++$n;
$name = $child ? 'child' . $n : $n;
$t = array_filter(get_pattern($contents[ $k ]));
$t_s = the_shortcodes($out2, $contents[ $k ], true);
$output[ $name ] = array('name' => $parents[ $k ]);
$output[ $name ]['atts'] = parse_atts($atts[ $k ]);
$output[ $name ]['original_content'] = $contents[ $k ];
$output[ $name ]['content'] = ! empty($t) && ! empty($t_s) ? $t_s : $contents[ $k ];
}
}
return array_values($output);
}
用法:
$text = "[parrent_shortcode attribute='1' attribute2='a b c']
[shortcode atrribute1=true attribute2=\"j'aime\"]This is first content[/shortcode]
[shortcode atrribute1=false]This is [shortcode/] content[/shortcode]
[/parrent_shortcode]
";
$output = array();
$output = the_shortcodes($output, $text);
var_dump(array_values($output));
此相呼应:
array (
0 =>
array (
'name' => 'parrent_shortcode',
'atts' =>
array (
'attribute' => 1,
'attribute2' => 'a b c',
),
'original_content' => '
[shortcode atrribute1=true attribute2="j\'aime"]This is first content[/shortcode]
[shortcode atrribute1=false]This is [shortcode/] content[/shortcode]
',
'content' =>
array (
'child1' =>
array (
'name' => 'shortcode',
'atts' =>
array (
'atrribute1' => true,
'attribute2' => 'j\'aime',
),
'original_content' => 'This is first content',
'content' => 'This is first content',
),
'child2' =>
array (
'name' => 'shortcode',
'atts' =>
array (
'atrribute1' => false,
),
'original_content' => 'This is [shortcode/] content',
'content' =>
array (
0 =>
array (
'name' => 'shortcode',
'atts' =>
array (
),
'original_content' => '',
'content' => '',
),
),
),
),
),
)
这真是太棒了:) – Domagoj