在 PHP
语言中操作字符串和数组一般使用 str_*
和 array_*
的系列函数,这些函数由于历史原因,命名和参数顺序风格不统一,广为开发者诟病,PHP
语言标准库中暂未提供 OO
风格的 Array
和 String
类库,开发者使用起来不是很便利,在 Swoole
中我们提供了一 swoole_array
和 swoole_string
对字符串和数组操作进行了面向对象封装,可以使用完全面向对象风格进行 Array
和 String
编程。
Swoole
项目:可直接使用Swoole
项目,使用 composer require swoole/library
引入绝大部分方法提供了链式风格
支持,可以一路使用 ->
编写逻辑。底层类库使用了 declare(strict_types=1)
强类型,使用 phpstorm
工具时,可以实现完全自动提示和自动完成。
$array1 = swoole_array(['hello', 'world']);
$array2 = swoole_array(['hello' => 1, 'world' => 2]);
$array3 = swoole_array_list('hello', 'world', 'swoole', 'php');
// Bytes 字符串
$string1 = swoole_string('hello world, php java, swoole');
// 宽字符串
$string2 = swoole_mbstring('我是中国人');
// 返回 5
$string2->length();
// 获取
$value1 = $array1->get(0);
$value2 = $array2->get('hello');
// 数组的第一个元素
$first = $array->first();
// 数组的最后一个元素
$last = $array->last();
// 设置
$array1->set(0, 'swoole');
$array2->set('world', 9);
// 在末尾追加
$array1->pushBack('java');
// 在头部插入
$array1->pushFront('go');
// 在中间 offset 2 插入
$array1->insert(2, 'rust');
$array1->append('rust')->append('c ')->append('swift', 'kotlin');
$array2->set('rust', 99)->set('c ', 88)->set('kotlin', 77);
// 按 key 删除
$array1->delete(0);
$array2->delete('worker');
// 按 value 删除
$array1->remove('hello');
使用contains()
方法可以判断数组或字符串中是否包含某个元素。
$array1->contains('java');
$string1->contains('php');
使用startsWith()
和endsWith()
方法判断字符串开头和结尾是否为指定的值。
$str = swoole_string('php and swoole');
$str->startsWith('php'); //true
$str->startsWith('java'); //false
$str->endsWith('swoole'); //true
$str->endsWith('golang'); //false
// 查找数组中是否有某个值,存在则返回其 key
$key = $array1->search('java');
String
与Array
可以结合使用。
$s = '11, 33, 22, 44,12,32,55,23,19,23';
$data = swoole_string($s)
->split(',')
->each(fn(&$item) => $item = intval($item))
/* sort()
->unique()
->join('-')
->contains('-44-');
var_dump($data);
split
按照,
分割为数组$fn
函数将元素转换为整数-
组合成为字符串-44-
对 swoole_array
对象元素操作时,底层会自动判断它的类型,如果为数组或字符串,底层会递归封装。
$array = swoole_array_list(['hello' => 'swoole']);
$array->get(0)->get('hello')->contains('swoole');
底层实现其实就是基于str_
和array_
相关函数进行面向对象封装,没有过多性能损耗,仅为一次method
调用开销。我们编写了严格的单测覆盖到每个API
,保证其可靠性。
性能方面,使用String::contains()
执行100
万次,与直接运行 php strpos
差距不大。
swoole_string: 0.059892892837524s, php_string: 0.033510208129883s
GitHub
: https://github.com/swoole/library 如果您对此项目感兴趣,可以参与到我们的开发工作中,期待您的 Pull Request
。
作者:韩天峰
链接:https://segmentfault.com/a/1190000022987724?_ea=55618049
来源:SegmentFault 思否
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
您可能感兴趣的文章:
参与评论
手机查看
返回顶部