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  ', ...);
      
    评论

报告相同问题?

悬赏问题

  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?