在 PHP 中将字符串拆分为多个分隔符
我可以使用 preg_split
用逗号分割字符串,例如
$words = preg_split('/[,]/', $string);
如何使用点、空格和分号来分割字符串?
附言。我在 PHP preg_split 页面上找不到任何相关示例,这就是我问的原因。
I can split a string with a comma using preg_split
, like
$words = preg_split('/[,]/', $string);
How can I use a dot, a space and a semicolon to split string with any of these?
PS. I couldn't find any relevant example on the PHP preg_split page, that's why I am asking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
模式解释
[]
是一个字符类,字符类由多个字符组成,并与类内的字符之一匹配
。 匹配
.
字符,这不需要在内部字符类中进行转义。尽管不在字符类中时需要转义,因为.
表示“匹配任何字符”。\s
匹配空格;
在分号上分割,这不需要转义,因为它没有特殊含义。末尾的
+
确保分割字符后面的空格不会显示为匹配项Try this:
The Pattern explained
[]
is a character class, a character class consists of multiple characters and matches to one of the characters which are inside the class.
matches the.
Character, this does not need to be escaped inside character classes. Though this needs to be escaped when not in a character class, because.
means "match any character".\s
matches whitespace;
to split on the semicolon, this needs not to be escaped, because it has not special meaning.The
+
at the end ensures that spaces after the split characters do not show up as matches这些例子就在那里,也许不是字面上的,而是带有多个分隔符选项的分割
The examples are there, not literally perhaps, but a split with multiple options for delimiter
像这样的东西?
结果:
something like this?
result:
只需将这些字符添加到您的表达式中
编辑:感谢 Igoris Azanovas,不需要在字符类中转义点;)
just add these chars to your expression
EDIT: thanks to Igoris Azanovas, escaping dot in character class is not needed ;)