You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建短代码函数在页面运行脚本?CMS自定义CKEditor场景问题

解决CKEditor短代码替换的顺序错乱与数字1显示问题

看起来你已经在短代码解析的路上走了大半,现在遇到的两个核心问题其实很好解决——数字1是include的默认返回值,而顺序错乱则是因为替换逻辑和输出捕获的方式不对。咱们一步步来修复:

一、为什么会显示数字1?

当你用$html = include("$arg1");时,include函数在成功加载脚本后默认返回1,除非被包含的脚本里有return语句。所以你其实是把1替换到了短代码的位置,这就是那些数字的来源。

解决方法是让被包含的脚本返回输出内容,而不是直接echo。比如你的simple-gallery.php可以改成这样:

<?php
// 开启输出缓冲,捕获脚本的所有输出
ob_start();

// 原来的画廊逻辑示例
$galleryId = $args[0] ?? 1;
$perPage = $args[1] ?? 3;
echo "<div class='gallery'>Gallery #$galleryId (show $perPage items)</div>";

// 取出缓冲内容并清空缓冲,最后返回内容
$output = ob_get_clean();
return $output;

二、修复顺序错乱与替换逻辑

你的循环里用preg_replace替换时,每次修改$introtext后,若正则匹配不够精准可能会出现意外替换。另外,要确保每个短代码都被精准遍历和替换。

修改后的主代码如下:

// 匹配所有{...}格式的短代码,转义大括号避免正则冲突
preg_match_all("/\{([^{}]+)\}/", $introtext, $results);

foreach($results[1] as $shortcode) {
    // 拆分短代码为脚本名和参数(按空格分割)
    $parts = preg_split('/\s+/', trim($shortcode));
    $scriptName = array_shift($parts);
    $args = $parts; // 剩下的内容作为参数数组

    // 先检查脚本是否存在,避免报错
    if (file_exists($scriptName)) {
        // 加载脚本并获取返回的HTML内容
        $html = include($scriptName);
        // 用preg_quote处理短代码中的特殊字符,确保精准替换
        $introtext = preg_replace("/\{" . preg_quote($shortcode, '/') . "\}/", $html, $introtext);
    } else {
        // 脚本不存在时,替换成提示(也可以保留原短代码)
        $introtext = preg_replace("/\{" . preg_quote($shortcode, '/') . "\}/", "[Missing script: $scriptName]", $introtext);
    }
}

echo $introtext;

三、支持你偏好的URL参数格式(可选)

如果你想支持{gallery.php?id=1&opt=3}这种格式,可以调整参数解析逻辑,兼容两种参数写法:

foreach($results[1] as $shortcode) {
    if (strpos($shortcode, '?') !== false) {
        // 处理URL参数格式
        list($scriptName, $queryString) = explode('?', $shortcode, 2);
        parse_str($queryString, $args);
    } else {
        // 处理空格分隔的参数格式
        $parts = preg_split('/\s+/', trim($shortcode));
        $scriptName = array_shift($parts);
        $args = $parts;
    }

    // 后续加载脚本和替换逻辑和之前一致
    if (file_exists($scriptName)) {
        $html = include($scriptName);
        $introtext = preg_replace("/\{" . preg_quote($shortcode, '/') . "\}/", $html, $introtext);
    }
}

这样不管管理员输入哪种格式的短代码,都能正确解析并替换。

内容的提问来源于stack exchange,提问作者Bob M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:33:32