我尝试使用regex / preg_match_all短代码(在wordpress中)以获取特定的属性值,但是我的php代码部分工作...
事实上,我成功使用了正则表达式父代短代码而不是儿童短代码。
我的短代码看起来像这样:
[to_custom_font family="Lato;900italic" decoration="" style="normal"]Content[/to_custom_font]
这是我的php代码:
preg_match_all("/$pattern/",$post_content,$matches);
$to_shortcode = array_keys($matches[2],'to_custom_font');
if (!empty($to_shortcode)) {
foreach($to_shortcode as $sc) {
preg_match('/family="([^"]+)"/', $matches[3][$sc], $match);
$font_infos = explode(';',$match[1]);
$family = $font_infos[0];
$variant = $font_infos[1];
$font = $family.':'.$variant;
if(!in_array($font, $available_families)){
$available_font = array_merge($available_font, array($font => $post_id));
}
}
}
它适用于父短信码,但不适用于儿童短码:
[to_custom_font family="Lato;900italic" decoration="" style="normal"]Content[/to_custom_font] //parent shortcode
[to_section attr="" attr3=""]
[to_custom_font family="Lato;900italic" decoration="" style="normal"]Content[/to_custom_font]//child shortcode
[/to_section]
问题似乎来自这里:
preg_match_all("/$pattern/",$post_content,$matches);
$matches
仅返回父短信码。我需要得到所有孩子的水平...
我对此代码的目标是获取所有值family=""
属性。也许还有更好的方法......
答案 0 :(得分:1)
如果我理解你的问题,这可能就是你需要的
$string = '[to_custom_font family="Lato;900italic" decoration="" style="normal"]Content[/to_custom_font] //parent shortcode[to_section attr="" attr3=""][to_custom_font family="Lato;900italic" decoration="" style="normal"]Content[/to_custom_font]//child shortcode[/to_section]';
preg_match_all('/family="([^"]+)"/', $string, $matches);
foreach ($matches[1] as $match) {
echo $match . "\n";
}
// or use print_r() to see the whole array
print_r($matches);
?>
输出:
Lato;900italic
Lato;900italic
Array
(
[0] => Array
(
[0] => family="Lato;900italic"
[1] => family="Lato;900italic"
)
[1] => Array
(
[0] => Lato;900italic
[1] => Lato;900italic
)
)