hazbo/simpletags

此包的最新版本(dev-master)没有提供许可证信息。

SimpleTags库,用于解析{各种标签}

dev-master 2014-01-28 09:42 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:16:29 UTC


README

描述

Simpletags正如其名...是一种简单的方式在PHP应用程序中使用标签。这允许您拥有如下所示的标签

{something:other}
{date format="m/d/Y"}

{blog:entries count="5"}
Stuff here
{/blog:entries}

安装

hazbo/simpletags添加到您的composer.json文件中

{
    "require" : {
        "hazbo/simpletags"
    }
}

运行composer update

使用

您可以将以下选项的配置数组发送到构造函数(这些是默认选项)

array(
    'l_delim' => '{',
    'r_delim' => '{',
    'trigger' => '',
);

您也可以通过以下函数设置定界符和触发器

$simpletags = new SimpleTag();
$simpletags->setDelimitiers('{', '}');
$simpletags->setTrigger('foo:');

要解析一段文本,只需调用parse()函数。parse函数接受3个参数

  1. $content - 要解析的内容
  2. [可选] $data - 一个键值数组,用于替换标签变量(更多内容见下文)
  3. [可选] $callback - 一个回调函数,将为每个标签调用。

正常返回

如果没有指定回调,则函数将返回一个数组。假设这是您发送的内容

Hello there.

{rest:get url="http://example.com/api" type="json"}
Stuff here
{/rest:get}

Bye.

解析将返回

Array
(
    [content] => Hello there.

marker_0k0dj3j4nJHDj22j

Bye.
    [tags] => Array
        (
            [0] => Array
                (
                    [full_tag] => {rest:get url="http://example.com/api" type="json"}
Stuff here
{/rest:get}
                    [attributes] => Array
                        (
                            [url] => http://example.com/api
                            [type] => json
                        )

                    [segments] => Array
                        (
                            [0] => rest
                            [1] => get
                        )

                    [content] => 
Stuff here

                    [marker] => marker_0k0dj3j4nJHDj22j
                )

        )

)

使用数据数组

数据数组是一个键值数组,其内容将替换具有相同名称的标签。例如

{foo:bar}

当将以下数据数组发送到解析函数时,将替换为"Hello World"

$data['foo']['bar'] = "Hello World"

您还可以使用标签对来遍历数据

标签

{books}
{title} by {author}<br />
{/books}

数据

$data = array(
    'books' => array(
        array(
            'title' => 'PHP for Dummies',
            'author' => 'John Doe'
        ),
        array(
            'title' => 'CodeIgniter for Dummies',
            'author' => 'Jane Doe'
        )
    )
);

输出结果

PHP for Dummies by John Doe
CodeIgniter for Dummies by Jane Doe

回调函数

回调函数必须是is_callable()接受的格式(通常是数组(对象,方法))。回调函数应该接受1个参数(一个数组)。

回调函数将被发送一个包含标签信息的数组。考虑以下

{rest:get url="http://example.com/api" type="json"}
Stuff here
{/rest:get}

将发送以下数组到回调函数

Array
(
    [full_tag] => {rest:get url="http://example.com/api" type="json"}
Stuff here
{/rest:get}
    [attributes] => Array
        (
            [url] => http://example.com/api
            [type] => json
        )

    [segments] => Array
        (
            [0] => rest
            [1] => get
        )

    [content] => 
Stuff here

    [marker] => marker_0k0dj3j4nJHDj22j
)