最近使用s9e做内容解析,但是由于没啥中文的资料和文档,记录一下。
文档地址:https://s9etextformatter.readthedocs.io/
使用:
1.在composer中加入s9e的扩展包
"require" : {
"s9e/text-formatter": "^2.4",
},
2.增加tag支持##解析和渲染
$configurator = new s9e\TextFormatter\Configurator;
//增加标签
$tag = $configurator->tags->add('topic');
//增加标签属性
$tag->attributes->add('id');
//设置属性的值
$tag->filterChain->prepend([static::class, 'addTopicId']);
//设置渲染模板
$tag->template = '<span id="topic" value="{@id}"><xsl:apply-templates/></span>';
//设置标签正则匹配规则
$configurator->Preg->match('/\B#(?<topic>[\x{4e00}-\x{9fa5}\w]+)#/ui', $tagName);
addTopicId函数用来在数据库中创建、查找话题ID
public static function addTopicId($tag)
{
$topic = Topic::firstOrCreate(
['content' => $tag->getAttribute('topic')]
);
$tag->setAttribute('id', $topic->id);
return true;
}
3.渲染数据
$renderer = s9e\TextFormatter\Renderer::getRenderer();
$parser = s9e\TextFormatter\Parser::getParser();
$html = $renderer->render($content);
$text = $parser->parse($content);
原文 "#话题#"
数据库中存储 ”<topic id="1">#话题#</topic>“
渲染后的数据 ”<span id="topic" value="1">#话题#</span>“