use*_*521 2 php delimiter preg-split
我读了其他相关的帖子,但不可能让它适用于我的情况.
我有以下文字:
This. Is a test. I show. You.
Run Code Online (Sandbox Code Playgroud)
我想使用preg_split使用分隔符'.'(点+空格),但我需要在返回的数组中保留分隔符.这是需要的结果:
array(
'0' => 'This.',
'1' => 'Is a test.',
'2' => 'I show.',
'3' => 'You.',
);
Run Code Online (Sandbox Code Playgroud)
我已经尝试过的:
preg_split("/(\.\s/)", $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
Run Code Online (Sandbox Code Playgroud)
使用零宽度断言(这里是一个lookbehind):
$result = preg_split('~(?<=\.)\s~', $text, -1, PREG_SPLIT_NO_EMPTY);
Run Code Online (Sandbox Code Playgroud)
或者您可以使用\K从整个匹配中删除左侧所有内容的功能:
$result = preg_split('~\.\K\s~', $text, -1, PREG_SPLIT_NO_EMPTY);
Run Code Online (Sandbox Code Playgroud)
没有正则表达式(如果空格只是空格,如果最后一个点后面没有空格):
$chunks = explode('. ', $text);
$last = array_pop($chunks);
$result = array_map(function ($i) { return $i . '.'; }, $chunks);
$result[] = $last;
Run Code Online (Sandbox Code Playgroud)
或更好:
$result = explode(' #&§', strtr($text, ['. '=>'. #&§']));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
846 次 |
| 最近记录: |