更新@Duco 的sn-p,看起来,当我们有类似的东西时,它会被空间破坏
[Image source="myimage.jpg" alt="My Image"]
到现在的:
function handleShortcodes($content, $shortcodes){
function read_attr($attr) {
$atList = [];
if (preg_match_all('/\s*(?:([a-z0-9-]+)\s*=\s*"([^"]*)")|(?:\s+([a-z0-9-]+)(?=\s*|>|\s+[a..z0-9]+))/i', $attr, $m)) {
for ($i = 0; $i < count($m[0]); $i++) {
if ($m[3][$i])
$atList[$m[3][$i]] = null;
else
$atList[$m[1][$i]] = $m[2][$i];
}
}
return $atList;
}
//Loop through all shortcodes
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("/\[".$key."(.*?)\]/", $content, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$params = read_attr($temp);
$content = str_replace($actual_string[$i], $function($params), $content);
$i++;
}
}
}
return $content;
}
$content = '[image source="one" alt="one two"]';
结果:
array(
[source] => myimage.jpg,
[alt] => My Image
)
更新(2020 年 2 月 11 日)
它似乎在 preg_match 下遵循正则表达式仅标识具有属性的短代码
preg_match_all("/\[".$key." (.+?)\]/", $content, $dat);
使其正常使用 [contact-form] 或 [mynotes]。我们可以将以下内容更改为
preg_match_all("/\[".$key."(.*?)\]/", $content, $dat);