0

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

就像,这是我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 无关,它是一个自定义脚本。

4

1 回答 1

1

我相信问题可能出在您的function gallery($att, $cont).
如果该函数使用echoorprint代替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

于 2013-10-04T04:49:53.300 回答