enesakarsu/shortcode-hunter

PHP Shortcode Hunter - PHP 短代码类,嵌套短代码和自定义短代码

v0.1 2021-11-19 18:55 UTC

This package is auto-updated.

Last update: 2024-09-26 03:04:07 UTC


README

Shortcode Hunter - PHP 短代码类,嵌套短代码和自定义短代码

安装

composer require enesakarsu/shortcode-hunter

短代码的语法

短代码用方括号书写。每个打开的短代码都应该关闭。使用示例:

[example]shortcode[/example] and example text

如果您想的话,可以向短代码发送参数。参数用两个大括号书写。使用示例:

[post id={{22}}][/post]
and
[text color={{red}}]colored text[/text]

为什么使用短代码?

您可以在文本中捕获短代码并使它们执行您想要的任何操作。

示例:[post id={{1}}][/post]

我们可以将此短代码捕获到文本中,并从数据库中获取ID值为1的内容。

示例:[date][/date]

我们可以创建一个名为“date”的短代码,并打印当前时间到文本中。

您可以做到的事情完全取决于您的想象力。

使用示例

创建短代码

要创建短代码,打开shortcode-hunter/src/shortcodes.php文件,并创建如下示例中的短代码。在创建短代码时,我们将我们的短代码名称作为第一个参数,我们想要运行的函数名称作为第二个参数。

普通函数

$shortcode->create("example", "exampleFunction");

类方法

$shortcode->create("example", "class@method");

在上面的例子中,我们要求它为“example”短代码运行名为“exampleFunction”的函数。现在让我们在shortcode-hunter/src/functions.php文件中创建这个函数。

注意

要创建的函数的第一个参数应该是 $values,第二个参数应该是 $content。否则,无法访问参数和内容。

function exampleFunction($values, $content){
return "hello";
}

解析短代码

创建一个index.php文件,并将shortcode-hunter类包含在文件中。然后向短代码的unparse方法发送一些文本作为参数。

<?php
include "shortcode-hunter/src/hunter.php";

$text = "Some text and [example]shortcode[/example]";

echo $shortcode->parse($text);

?>

如果我运行index.php文件,我将得到的输出是

输出:hello

访问短代码的内容

如果我想访问短代码的内容;

function exampleFunction($values, $content){
return $content;
}

输出:shortcode

获取发送到短代码的参数

如果向短代码发送参数,我们可以这样捕获它们:[example id={{22}}]shortcode[/example]

function exampleFunction($values, $content){
return $values["id"];
}

输出:22

注意

如果短代码将要运行的函数中用echo而不是return,它将出现在文本的开头。为了避免这种情况,您需要进行输出缓冲。

ob_start();

//your codes
//your codes

$output = ob_get_contents();
ob_end_clean();

return $output;

示例;

function exampleFunction($values, $content){

ob_start();

$fruits = ["apple", "banana", "strawberry"];

foreach($fruits as $fruit){
echo $fruit;
}

$output = ob_get_contents();
ob_end_clean();

return $output;

}