Splitting a string on multiple separators in PHP

前端 未结 6 494
走了就别回头了
走了就别回头了 2021-01-25 03:50

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

相关标签:
6条回答
  • 2021-01-25 04:36
    $words = preg_split('/[,\.\s;]/', $string);
    
    0 讨论(0)
  • 2021-01-25 04:38

    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
    )
    
    0 讨论(0)
  • 2021-01-25 04:48

    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

    0 讨论(0)
  • 2021-01-25 04:52
    $words = preg_split('/[\,\.\ ]/', $string);
    
    0 讨论(0)
  • 2021-01-25 04:56

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

    $words = preg_split('/[ ;.,]/', $string);
    
    0 讨论(0)
  • 2021-01-25 04:57

    just add these chars to your expression

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

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

    0 讨论(0)
提交回复
热议问题