PHP - 简单的短代码解析器,输出顺序错误

时间:2013-10-04 04:42:28

标签: php

我有一个简单的函数来解析短代码标签及其属性, 但它在输出方面有一些问题。

就像,这是我的content字符串中的短代码:

$content = 'This is lorem ispium test [gallery image="10"] and text continues...'

我希望结果输出如下:

This is lorem ispium test 
----------------------------------------------
|        This is output of gallery            |

-----------------------------------------------
and text continues...

但现在短代码不会在调用短代码的地方渲染,而不是在顶部渲染短代码。像:

    ----------------------------------------------
    |        This is output of gallery            |

    -----------------------------------------------
    This is lorem ispium test and text continues...

请告诉我如何在其被称为

的地方呈现短代码
function shortcode($content) {

    $shortcodes = implode('|', array_map('preg_quote', get('shortcodes')));
    $pattern    = "/(.?)\[($shortcodes)(.*?)(\/)?\](?(4)|(?:(.+?)\[\/\s*\\2\s*\]))?(.?)/s";

    echo preg_replace_callback($pattern, array($this,'handleShortcode'), $content);
}

function handleShortcode($matches) {

    $prefix    = $matches[1];
    $suffix    = $matches[6];
    $shortcode = .$matches[2];

    // allow for escaping shortcodes by enclosing them in double brackets ([[shortcode]])
    if($prefix == '[' && $suffix == ']') {
        return substr($matches[0], 1, -1);
    }

    $attributes = array(); // Parse attributes into into this array.

    if(preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) {
        foreach($match as $attribute) {
            if(!empty($attribute[4])) {
                $attributes[strtolower($attribute[1])] = $attribute[4];
            } elseif(!empty($attribute[3])) {
                $attributes[strtolower($attribute[1])] = $attribute[3];
            }
        }
    }
    //callback to gallery
    return $prefix. call_user_func(array($this,$shortcode), $attributes, $matches[5], $shortcode) . $suffix;
}


function gallery($att, $cont){
    //gallery output
}

请注意:它与wordpress无关,它是一个自定义脚本。

1 个答案:

答案 0 :(得分:1)

我认为问题可能出在您的function gallery($att, $cont) 如果该函数使用echoprint而不是return,那么在实际内容出现之前显示它是完全合理的。

修改
如果您无法更改图库代码,则可以使用output buffering

function handleShortcode($matches) {
  ...
  ob_start();
  call_user_func(array($this,$shortcode), $attributes, $matches[5], $shortcode);
  $gallery_output = ob_get_contents();
  ob_end_clean();

  return $prefix . $gallery_output . $suffix;
}

相关阅读材料:
PHP ob_start
PHP ob_get_contents