xvmqC1Ye - 4天前注册会员;
mbtdr3ev - 9天前注册会员;
3n44fZgo - 29天前注册会员;
73n5lsCR - 43天前注册会员;
NaZ2pUfG - 52天前注册会员;
加入我们(63 )

php短代码解析,基本通用可应用到typecho,emlog,zblog等博客程序中,已经封装。附demo

php短代码解析,基本通用可应用到typecho,emlog,zblog等博客程序中,已经封装

其实就是将wp那一套搬过来了,顺便封装了一下,让代码更得心应手。

什么是短代码?

短代码是一种简化博客程序代码编写的技术。通过使用短代码,您可以在文章或页面中插入特定的功能或内容,而无需手动编写复杂的HTML或PHP代码。短代码可以帮助您更快速地创建博客内容,提高效率。

短代码的好处

短代码带来了许多好处,包括:

  • 简化代码编写:使用短代码,您可以通过简单的标记插入复杂的功能或内容,而无需编写大量的代码。这使得您可以更轻松地添加各种元素,如图像、音频、视频、表格等。

  • 提高可读性:短代码的语法通常较为简洁,易于理解和阅读。通过使用短代码,您可以使代码更加清晰明了,便于其他人理解和维护。

  • 增加灵活性:短代码可以根据需要进行定制和扩展。您可以根据自己的需求创建自定义的短代码,并将其应用到不同的博客程序中,从而提供更多的灵活性和自定义选项。

  • 方便的代码管理:通过封装短代码,我们可以将常用的功能和布局模块化,使其更易于维护和管理。这样一来,您可以在需要的时候轻松重复使用这些代码,无需每次都从头开始编写。

配合JS代码,应该可以做到更“傻瓜化”使用

使用非常简单。
一共三个文件
codeAnalysis.php

<?php 
class Content{

/**************解析功能区域搬WordPress的,这里不需要改动***************************/

/**
 * 获取匹配短代码的正则表达式
 * @param null $tagnames
 * @return string
 * @link https://github.com/WordPress/WordPress/blob/master/wp-includes/shortcodes.php#L254
 */
public static function get_shortcode_regex($tagnames = null)
{
    global $shortcode_tags;
    if (empty($tagnames)) {
        $tagnames = array_keys($shortcode_tags);
    }
    $tagregexp = join('|', array_map('preg_quote', $tagnames));
    // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcode_tag()
    // Also, see shortcode_unautop() and shortcode.js.
    // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
    return
        '\\['                                // Opening bracket
        . '(\\[?)'                           // 1: Optional second opening bracket for escaping shortcodes: [[tag]]
        . "($tagregexp)"                     // 2: Shortcode name
        . '(?![\\w-])'                       // Not followed by word character or hyphen
        . '('                                // 3: Unroll the loop: Inside the opening shortcode tag
        . '[^\\]\\/]*'                   // Not a closing bracket or forward slash
        . '(?:'
        . '\\/(?!\\])'               // A forward slash not followed by a closing bracket
        . '[^\\]\\/]*'               // Not a closing bracket or forward slash
        . ')*?'
        . ')'
        . '(?:'
        . '(\\/)'                        // 4: Self closing tag ...
        . '\\]'                          // ... and closing bracket
        . '|'
        . '\\]'                          // Closing bracket
        . '(?:'
        . '('                        // 5: Unroll the loop: Optionally, anything between the opening and closing shortcode tags
        . '[^\\[]*+'             // Not an opening bracket
        . '(?:'
        . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
        . '[^\\[]*+'         // Not an opening bracket
        . ')*+'
        . ')'
        . '\\[\\/\\2\\]'             // Closing shortcode tag
        . ')?'
        . ')'
        . '(\\]?)';                          // 6: Optional second closing brocket for escaping shortcodes: [[tag]]
    // phpcs:enable
}

/**
 * 获取短代码属性数组
 * @param $text
 * @return array|string
 * @link https://github.com/WordPress/WordPress/blob/master/wp-includes/shortcodes.php#L508
 */
public static function shortcode_parse_atts($text)
{
    $atts = array();
    $pattern = self::get_shortcode_atts_regex();
    $text = preg_replace("/[\x{00a0}\x{200b}]+/u", ' ', $text);
    if (preg_match_all($pattern, $text, $match, PREG_SET_ORDER)) {
        foreach ($match as $m) {
            if (!empty($m[1])) {
                $atts[strtolower($m[1])] = stripcslashes($m[2]);
            } elseif (!empty($m[3])) {
                $atts[strtolower($m[3])] = stripcslashes($m[4]);
            } elseif (!empty($m[5])) {
                $atts[strtolower($m[5])] = stripcslashes($m[6]);
            } elseif (isset($m[7]) && strlen($m[7])) {
                $atts[] = stripcslashes($m[7]);
            } elseif (isset($m[8]) && strlen($m[8])) {
                $atts[] = stripcslashes($m[8]);
            } elseif (isset($m[9])) {
                $atts[] = stripcslashes($m[9]);
            }
        }
        // Reject any unclosed HTML elements
        foreach ($atts as &$value) {
            if (false !== strpos($value, '<')) {
                if (1 !== preg_match('/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value)) {
                    $value = '';
                }
            }
        }
    } else {
        $atts = ltrim($text);
    }
    return $atts;
}

/**
 * Retrieve the shortcode attributes regex.
 *
 * @return string The shortcode attribute regular expression
 * @since 4.4.0
 *
 */
public static function get_shortcode_atts_regex()
{
    return '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|\'([^\']*)\'(?:\s|$)|(\S+)(?:\s|$)/';
}

/**************解析功能区域搬WordPress的,这里不需要改动***************************/
}

codeParser.php

<?php
include_once __DIR__ . '/codeAnalysis.php';
class CodeParser
{
    private static $shortcodes = array();

    public static function registerShortcode($codename, $functionname)
    {
        self::$shortcodes[] = array(
            'codename' => $codename,
            'functionname' => $functionname
        );
    }

    public static function parseContent($content, $logid = null)
    {
        foreach (self::$shortcodes as $shortcode) {
            $codename = $shortcode['codename'];
            $functionname = $shortcode['functionname'];

            if (strpos($content, "[$codename") !== false) {
                $pattern = Content::get_shortcode_regex(array($codename));
                $content = preg_replace_callback("/$pattern/", function ($matches) use ($functionname, $logid) {
                    $matches[3] = Content::shortcode_parse_atts($matches[3]);
                    return call_user_func($functionname, $matches, $logid);
                }, $content);
            }
        }

        return $content;
    }
}

前面两个文件都不需要动,只要引用就行
下面的是使用demo的php

<?php

include_once 'shortCode/codeParser.php';

// 注册代码
CodeParser::registerShortcode('info', 'infobleParseCallback');

// 注册的函数
function infobleParseCallback($matches, $array)
{
    /**
     * 关于$matches的解释
        $content = "[[info type=hhh]]内容[[/info]]";
        $matches[0]: 整个正则表达式匹配到的字符串,即 [info type='important']这是一段重要的内容[/info]。
        $matches[1]: 第一个括号捕获的内容,即短代码的开始标签中的 [。如果是双括号,那么可以判断不解析或者返回一个删除一个[的代码
        $matches[2]: 第二个括号捕获的内容,即短代码的名称,即 info。
        $matches[3]: 第三个括号捕获的内容,即短代码的属性,即 type='important'。
        $matches[4]: 第四个括号捕获的内容,为空,不知道是为啥。
        $matches[5]: 第五个括号捕获的内容,即短代码的内容。如果是有结束符的短代码,那么就是中间的内容。
        $matches[6]: 第六个括号捕获的内容,即短代码的结束标签中的 ]。只有双括号才有的值,那么可以判断不解析或者返回一个删除一个]的代码。
    **/
    print_r($matches);
    print_r($array);
}

// $content = "[[info type=hhh url=xxx]]内容[[/info]]";
$content = "{info type=hhh url=xxx}内容{/info}";
$array = ['123','456']; 
$processedContent = CodeParser::parseContent($content, $array);
// 输出处理后的内容
echo $processedContent;
echo "<br><br><br>";

是支持传参的,传数组。具体用法,大家随意发挥啦!

demo下载地址:

蓝奏云网盘下载

声明:本站原创文章文字版权归本站所有,转载务必注明作者和出处;本站转载文章仅仅代表原作者观点,不代表本站立场,图文版权归原作者所有。如有侵权,请联系我们删除。