使用 PHP 分割空格和括号 [英] Use PHP for splitting on spaces and brackets

查看:56
本文介绍了使用 PHP 分割空格和括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 $s 中有这个字符串:

I have this string in $s:

本说(#yellow)嘿

ben say (#yellow) hey

目前我正在使用:

$parts = array_filter(preg_split('/\s+/', $s));

所以我有一个数组元素的输出:

So i have an output of array elements:

[0] ben
[1] say
[2] (#yellow)
[3] hey

是否可以创建这样的数组结构:

Would it be possible to create an array structure like this:

[0] ben
[1] say
[2] (
[3] #yellow
[4] )
[5] hey

推荐答案

您可以通过 Lookahead 和 Lookbehind Zero-Width Assertions 拆分:

$parts = array_filter(preg_split('/\s+|(?=[()])|(?<=[()])/', $s));

这篇关于使用 PHP 分割空格和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆