dongtiao2105 2012-05-03 02:00
浏览 29

preg_split包含尾随空格的单词[关闭]

What's the regex to use in preg_split in this example?

Example

<?$a='Word  with  white   trailing   spaces.    ';

Output

Array(
[0] => 'Word  ',
[1] => 'with  ',
[2] => 'white   ',
[3] => 'trailing   ',
[3] => 'spaces.    '
)

I've no idea in regex in php. I just need to minimize the code. Maybe someone could help me and explain a little bit about the answered regex

  • 写回答

2条回答 默认 最新

  • dougou5844 2012-05-03 02:36
    关注

    Well, here's one option:

    array_map('join', 
      array_chunk(
        preg_split('/(\s+)/', $a, null, 
                   PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY),
        2));
    

    Taking it by steps.

    1. Split by any amount of whitespace - \s+

    2. But remember the whitespace - that's the parentheses and the PREG_SPLIT_DELIM_CAPTURE flag.

      This gives you an array that looks like this:

      array('Word', '  ', 'with', '  ', 'white', '   ',
            'trailing', '   ', 'spaces.', '    ')
      
    3. Pass the result to array_chunk with a chunk_size of 2.

      Now we have an array of 2-element arrays:

      array(array('Word', '  '), array('with', '  '), ... )
      
    4. Pass that result to array_map with a callback of join - which joins each pair of strings into one string, and gives us the desired result:

      array('Word  ', 'with  ', ...);
      
    评论

报告相同问题?