我尝试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=""
属性。也许有更好的方法…
如果我理解你的问题,这可能是你需要的
$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
)
)
PHP demo | Regex demo