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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵