mimrahe / striptags
PHP strip_tags 扩展库
1.3.0
2016-10-07 17:17 UTC
Requires (Dev)
- phpunit/phpunit: 5.5.5
This package is not auto-updated.
Last update: 2024-09-14 19:47:47 UTC
README
PHP 的 strip_tags() 函数只允许移除字符串作为第二个参数时不在其中的标签!我发现我需要一个只移除一些标签的解决方案!
StripTags 现在对我来说是一个解决方案!
如何安装
composer require mimrahe/striptags:1.3.0
或下载发布版压缩包
如何使用
命名空间
\Mimrahe\StripTags\Stripper;
移除某些标签
$stripTags = new Stripper('<b>some bold</b><a href="#">link</a>'); $stripedText = $stripTags->only(['b', 'p'])->strip(); echo $stripedText; // prints 'some bold<a href="#">link</a>'
移除除某些标签之外的所有标签
echo (new Stripper('<b>some bold</b><a href="#">link</a>'))->except(['a'])->strip(); // prints 'some bold<a href="#">link</a>'
循环使用示例
$stripper = new Stripper(); $stripper->only(['a', 'ul', 'li']); $textArray = [ // some texts that will be stripped ]; foreach($textArray as $text) { echo $stripper->on($text)->strip(); }
向 Stripper 提供一个数组
$stripper = new Stripper(); $stripper->only(['a', 'ul', 'li']); $textArray = [ // some texts that will be stripped ]; $strippedArray = $stripper->on($textArray)->strip();
技巧
- 你可以向方法 'on' 给出一个嵌套数组
过滤数组后再移除
$stripped = $stripper->on($textArray) ->filter(function($value, $key){ // some checks return $bool; }) ->strip();
在移除之前对数组进行一些操作
$stripped = $stripper->on($textArray) ->before(function(&$value, $key){ // do something on array values // note that $value must be as a reference // $key may be a reference }) ->strip();
在移除之后对数组元素进行一些操作
$stripped = $stripper->on($textArray) ->after(function(&$value, $key){ // do something on array values // note that $value must be as a reference // $key may be a reference }) ->strip();
方法
构造函数:Stripper 构造函数
new Stripper(array | string $subject = '');
参数
- $subject:strippers 工作上的文本或文本数组
返回:$this
on:指定 strippers 工作上的字符串或字符串数组(与构造函数相同)
$stripper->on(array | string $subject);
参数
- $subject:strippers 工作上的文本或文本数组
返回:$this
only:表示只移除这些标签
$stripper->only(array $tags);
参数
- $tags:要移除的标签数组
返回:$this
except:表示移除所有标签之外的一些(与 strip_tags 相同)
$stripper->except(array $tags);
参数
- $tags:不会移除的标签数组
返回:$this
技巧
- 在一段时间内只使用 only() 或 except() 中的一个,不要同时使用两者
filter:指定一个过滤主题数组的回调函数
$filter = function($value, $key){ // some check on value return $bool; } $stripper->filter(callable $filter);
参数
- $filter:一个闭包对数组进行过滤
返回:$this
before:指定一个在移除之前对数组元素产生影响的回调函数
$before = function(&$value, $key){ $value = '<br>' . $value; } $stripper->before(callable $before);
参数
- $before:一个闭包对数组元素产生影响
返回:$this
after:指定一个在移除之后对数组元素产生影响的回调函数
$after = function(&$value, $key){ $value = trim($value); } $stripper->after(callable $after);
参数
- $after:一个闭包对移除后的数组产生影响
返回:$this
strip:移除字符串或字符串数组
$stripper->strip();
返回:移除后的字符串或字符串数组
许可证
mimrahe/StripTags 在 MIT 许可证下授权
一个简短且简单的许可协议,只要求保留版权和许可证通知。受许可的作品、修改和更大的作品可以在不同的条款下分发,甚至不需要源代码。