pawelzny / trimmer
帮助将字符串裁剪到指定长度,并四舍五入到整词。
v2.0.3
2016-12-11 11:17 UTC
Requires
- php: ^5.6 || ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- phpunit/phpunit: ^5.6
This package is not auto-updated.
Last update: 2024-09-28 20:19:59 UTC
README
Trimmer 提供对字符串裁剪到指定长度方法的支持,以及带词感知的裁剪。不会将单词切断。
安装
如果您的操作系统全局安装了 composer
composer require pawelzny/trimmer
如果 composer 安装在您的项目目录中
php composer.phar require pawelzny/trimmer
开始使用
使用外观访问 Trimmer 对象或直接导入适当的类并使用。
裁剪到字符长度
<?PHP use Trimmer\Trim; $string = "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean."; $trim = Trim::chars($string, $length=40); echo $trim->trim(); // Far far away, behind the word mountai...
裁剪到单词长度
<?PHP use Trimmer\Trim; $string = "Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean."; $trim = Trim::words($string, $length=40); echo $trim->trim(); // Far far away, behind the word...
API
内置常量
<?PHP use Trimmer\Trim; echo Trim::ELLIPSIS; // ... echo Trim::EOL; // [end of line] echo Trim::SPACE; // [white space] echo Trim::TABULATOR; // [tab character] echo Trim::DEFAULT_DELIMITER; // ...
外观
Trim::chars()
CharsTrimmer: 构造函数(string: $string [, int: $length=null [, string: $delimiter=null]])
Trim::words()
WordsTrimmer: 构造函数(string: $string [, int: $length=null [, string: $delimiter=null]])
<?PHP use Trimmer\Trim; $chars = Trim::chars($string, $length=30, $delimiter=''); $words = Trim::words($string, $length=30, $delimiter='');
方法
Trim
string: trim()
对字符串进行裁剪并返回新的裁剪字符串
<?PHP use Trimmer\Trim; $string = 'Far far away, behind the word mountains'; Trim::chars($string)->trim(); Trim::words($string)->trim();
设置新长度
null: setLength(int: $length)
注意!:分隔符长度将从裁剪长度中自动减去。
<?PHP use Trimmer\Trim; $string = 'Far far away, behind the word mountains'; $trim = Trim::chars($string); $trim->setLength(30);
设置分隔符
null: setDelimiter(string: $delimiter)
<?PHP use Trimmer\Trim; $string = 'Far far away, behind the word mountains'; $trim = Trim::chars($string); $trim->setDelimiter('[read more]');
不使用外观
如果您不想使用外观,可以直接创建对象。
<?PHP use Trimmer\Services\WordsTrimmer; use Trimmer\Services\CharsTrimmer; use Trimmer\Trim; $string = 'Far far away, behind the word mountains'; $length = 30; $delimiter = Trim::DEFAULT_DELIMITER; $chars = new CharsTrimmer($string, $length, $delimiter); $newDelimiter = 'read more...'; $newLength = 40; $chars->setDelimiter($newDelimiter); $chars->setLength($newLength); $chars->trim(); $words = new WordsTrimmer($string, $length, $delimiter); $words->setDelimiter($newDelimiter); $words->setLength($newLength); $words->trim();