在这个例子中,preg_split中使用的正则表达式是什么?
例
<?$a='Word with white trailing spaces. ';
输出
Array(
[0] => 'Word ',
[1] => 'with ',
[2] => 'white ',
[3] => 'trailing ',
[3] => 'spaces. '
)
我不知道 php 中的正则表达式。我只需要最小化代码。也许有人可以帮助我并解释一下已回答的正则表达式
编辑:我看到OP想要一个解释。基本上()将一个单词''w+和任何非单词''W+分组,直到它找到一个新单词@为止)。所以(这里的任何内容)= $1
$str = "Word with white trailing spaces. ";
$split = preg_split("/('w+'W+)/", $str, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
var_dump($split);
好吧,这里有一个选项:
array_map('join',
array_chunk(
preg_split('/('s+)/', $a, null,
PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY),
2));
循序渐进。
按任意数量的空格分割 -
's+
但请记住空格 - 这是括号和PREG_SPLIT_DELIM_CAPTURE标志。
这为您提供了一个如下所示的数组:
array('Word', ' ', 'with', ' ', 'white', ' ', 'trailing', ' ', 'spaces.', ' ')
将结果传递给chunk_size为 2 的
array_chunk
。现在我们有一个 2 元素数组的数组:
array(array('Word', ' '), array('with', ' '), ... )
将该结果传递给带有
join
回调的array_map
- 它将每对字符串连接成一个字符串,并给我们所需的结果:array('Word ', 'with ', ...);