yarri / keywords-highlighter
在 HTML 字符串中突出显示关键词(通常是搜索查询)
v0.1.5
2021-11-15 15:21 UTC
Requires
- php: >=5.4.0
- ext-mbstring: *
Requires (Dev)
- atk14/tester: *
README
在 HTML 字符串中突出显示关键词(通常是搜索查询)。
基本用法
$html_text = '
<h1>The truth about pizza and beer</h1>
<p>
Beer and pizza.
It might be one of the most obvious food pairings on the planet...
</p>
';
$highlighter = new \Yarri\KeywordsHighlighter();
echo $highlighter->highlight($html_text,"pizza beer");
// <h1>The truth about <mark>pizza</mark> and <mark>beer</mark></h1>
//
// <p>
// <mark>Beer</mark> and <mark>pizza</mark>.
// It might be one of the most obvious food pairings on the planet...
// </p>
在构造函数的选项中可以覆盖默认的突出显示标签。
$highlighter = new \Yarri\KeywordsHighlighter([
"opening_tag" => '<span class="highlight">',
"closing_tag" => '</span>',
]);
echo $highlighter->highlight($html_text,"pizza beer");
// <h1>The truth about <span class="highlight">pizza</span> and <span class="highlight">beer</span></h1>
//
// <p>
// <span class="highlight">Beer</span> and <span class="highlight">pizza</span>.
// It might be one of the most obvious food pairings on the planet...
// </p>
KeywordsHighlighter 不会在 HTML 标签内部突出显示任何内容。
$html_text = '
<h1>The truth about the H1 element</h1>
';
$highlighter = new \Yarri\KeywordsHighlighter();
echo $highlighter->highlight($html_text,"h1");
// <h1>The truth about the <mark>H1</mark> element</h1>
安装
composer require yarri/keywords-highlighter
测试
composer update --dev
cd test
../vendor/bin/run_unit_tests