magnusjt/regtemplate_php

匹配模板并提取变量

1.0.0 2015-07-13 19:23 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:53:05 UTC


README

PHP类,用于将模板解析为正则表达式,用于匹配键值对。当你想从大量文本中创建正则表达式而不必处理正则表达式的所有细节(如转义文本)时,这很有用。

示例

$template->parse_template('Some number: {{ number|digits }}');
$name_value = $template->match('Some number: 5678');

/*
Should result in:

$name_value = [
    'number' => 5678
];
*/

安装

使用composer安装

composer require magnusjt/regtemplate_php

用法

请参阅examples文件夹中的示例。

基本用法示例

$template = \RegTemplate\RegTemplate('some/dir');

# Parse a template from a file inside the base directory
$template->parse_template_from_file('file_inside_some_dir.txt');

# Or parse from a string:
# $template->parse_template('Some number: {{ number|digits }}');

# Match an output string against the template. Name=>value array returned.
$name_value = $template->match('Some number: 64');

# Match all. If the regex matches several times, return a list of list of name=>value arrays:
$match_list = $template->match_all('Some number: 64, Some number: 65');

示例模板

Displaying numbers from index {{ index_name|word }}
Number of interesting events: {{ num_events|digits }}
Number of pages: {{ num_pages|digits }}
Status: {{ on_or_off|reg="(?:on|off)" }}

添加自定义规则

规则是一个名称和一个正则表达式。如果正则表达式有捕获组,确保它们是非捕获的,如下所示:(?:)。

$template->set_rule('digits', '\d+');
$template->set_rule('on_or_off', '(?:on|off)');

# Default rule if no rule is given in the template
$template->set_default_rule('\S+');

内联正则表达式

你可以在模板中使用内联正则表达式而不是规则。记住用反斜杠转义任何双引号。

$template->parse_template('{{ number|reg="\d\d\d" }}

忽略空白(默认开启)

通过将所有空白替换为单个空格来忽略任何多余的空白。你可以这样打开/关闭这个功能

$template->set_ignore_whitespace(true);

设置自定义变量标记(默认为'{{'和'}}')

如果你想要匹配的字符串包含默认变量标记,你可以这样更改标记

$template->set_variable_tokens('{{', '}}');

忽略变量(默认忽略变量名'any')

任何名为'any'的变量都会被忽略。它会被匹配,但不会返回。你可以这样更改要忽略的名称

$template->set_ignore_var_name('any');