OriginPHP Text

2.1.0 2021-01-19 09:21 UTC

This package is auto-updated.

Last update: 2024-09-19 17:17:51 UTC


README

license build coverage

文本工具包含许多方法,有助于处理字符串。

安装

安装此包

$ composer require originphp/text

将字符串转换为Ascii

将字符串转换为Ascii(转写)

$ascii = Text::toAscii('Ragnarr Loðbrók'); // Ragnarr Lodbrok

创建短链接

创建URL安全的短链接。字符串将转换为Ascii,然后未知字符将被分隔符替换。

$slug = Text::slug('Who is Ragnarr Loðbrók?'); // who-is-ragnarr-lodbrok

包含

检查字符串是否包含子字符串。

$result = Text::contains('foo','What is foo bar'); // true

获取字符串的部分

当你需要获取字符串中子字符串之前或之后的部分时

$result = Text::left('foo','What is foo bar'); // 'What is '
$result = Text::right('foo','What is foo bar'); //' bar'

检查字符串的开始和结束

$bool = Text::startsWith('What','What is foo bar'); // true
$bool = Text::endsWith('bar','What is foo bar'); // true

替换

用另一个字符串替换子字符串

$result = Text::replace('foo','***','What is foo bar'); // 'What is *** bar'
$result = Text::replace('foo','***','What is FOO bar',['insensitive'=>true]); // 'What is *** bar'

插入

使用占位符(字符串插值)将值插入到字符串中

$string = Text::insert('Record {id} has been updated',[
    'id'=>1234568
]); // Record 1234568 has been updated

另一个例子

$letter = file_get_contents('/directory/some-file');
$string = Text::insert($letter,[
    'salutation' => 'Mr.',
    'first_name' => 'Tony',
    'last_name' => 'Robbins',
    'address_1' => '100 Santa Monica Road',
]);

你也可以更改占位符

$string = Text::insert('Record :id has been updated',[
    'id'=>1234568,'before'=>':','after'=>''
    ]); // Record 1234568 has been updated

标记化

为了快速轻松地解析字符串,标记化方法使事情变得简单。默认情况下,tokenize 使用逗号 , 和引号 " 作为分隔符。

$string = '2019-07-10 13:30:00 192.168.1.22 "GET /users/login HTTP/1.0" 200 1024';
$result = Text::tokenize($string,['separator'=>' ']);

/*
// Will give you this
[
    '2019-07-10',
    '13:30:00',
    '192.168.1.22',
    'GET /users/login HTTP/1.0',
    '200',
    '1024'
];
*/

你也可以提供键,它们将被映射。

$string = '2019-07-10 13:30:00 192.168.1.22 "GET /users/login HTTP/1.0" 200 1024';
$result = Text::tokenize($string,[
    'separator'=>' ',
    'keys'=>['date','time','ip','request','code','bytes']
]);

/*
// Will give you this
[
    'date'=>'2019-07-10',
    'time'=>'13:30:00',
    'ip' => '192.168.1.22',
    'request' =>'GET /users/login HTTP/1.0',
    'code'=>'200',
    'bytes'=>'1024'
];
*/

截断

如果字符串长度超过特定长度,则截断字符串。默认长度为30。

$truncated = Text::truncate($string,['length'=>50,'end'=>'... truncated']);

换行

对字符串进行换行

$wrapped = Text::wordWrap($string); // default is 80
$wrapped = Text::wordWrap($string,['width'=>50]);

其他

其他有用的字符串函数(通过 mb_string

$lowerCase = Text::toLower($string);
$uppserCase = Text::toUpper($string);
$int = Text::length($string);