Splitting a string on multiple separators in PHP

柔情痞子 提交于 2019-12-02 09:14:25

问题


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.


回答1:


Try this:

<?php

$string = "foo bar baz; boo, bat";

$words = preg_split('/[,.\s;]+/', $string);

var_dump($words);
// -> ["foo", "bar", "baz", "boo", "bat"]

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




回答2:


The examples are there, not literally perhaps, but a split with multiple options for delimiter

$words = preg_split('/[ ;.,]/', $string);



回答3:


something like this?

<?php
$string = "blsdk.bldf,las;kbdl aksm,alskbdklasd";
$words = preg_split('/[,\ \.;]/', $string);

print_r( $words );

result:

Array
(
    [0] => blsdk
    [1] => bldf
    [2] => las
    [3] => kbdl
    [4] => aksm
    [5] => alskbdklasd
)



回答4:


$words = preg_split('/[\,\.\ ]/', $string);



回答5:


just add these chars to your expression

$words = preg_split('/[;,. ]/', $string);

EDIT: thanks to Igoris Azanovas, escaping dot in character class is not needed ;)




回答6:


$words = preg_split('/[,\.\s;]/', $string);


来源:https://stackoverflow.com/questions/6813007/splitting-a-string-on-multiple-separators-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!