PHP split string on word before colon

前端 未结 2 1863
半阙折子戏
半阙折子戏 2021-01-29 13:26

I have a string that looks like this:

aaaaa: lorem ipsum bb: dolor sit amet ccc: no pro movet

What would be the best way to split the string in

相关标签:
2条回答
  • 2021-01-29 14:01

    Your desired 1-dim array can be directly achieved with preg_split() as requested. preg_split() is a better choice for this task versus preg_match_all because the only unwanted characters are the delimiting spaces. preg_match_all() creates a more complexe array structure than you need, so there is the extra step of accessing the first subarray.

    My pattern will split the string on every space that is followed by one or more lowercase letters, then a colon.

    Code: (Demo)

    $string = 'aaaaa: lorem ipsum bb: dolor sit amet ccc: no pro movet';
    var_export(preg_split('/ (?=[a-z]+:)/', $string));
    

    Output:

    array (
      0 => 'aaaaa: lorem ipsum',
      1 => 'bb: dolor sit amet',
      2 => 'ccc: no pro movet',
    )
    
    0 讨论(0)
  • 2021-01-29 14:12

    For this kind of job, I'll use preg_match_all:

    $str = 'aaaaa: lorem ipsum bb: dolor sit amet ccc: no pro movet';
    preg_match_all('/\S+:.+?(?=\S+:|$)/', $str, $m);
    print_r($m);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => aaaaa: lorem ipsum 
                [1] => bb: dolor sit amet 
                [2] => ccc: no pro movet
            )
    
    )
    

    Explanation:

    \S+:        : 1 or more NON space followed by colon
    .+?         : 1 or more any character not greedy
    (?=\S+:|$)  : lookahead, make sure we have 1 or more NON space followed by colon or end of string
    
    0 讨论(0)
提交回复
热议问题