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 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法
  • ¥15 dnat基础问题,本机发出,别人返回的包,不能命中