如何按字母后按句点分割?
我想按照字母后按句点的规则分割文本。所以我这样做:
$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/\w\./", $text);
print_r($splitted_text);
然后我得到这个:
Array ( [0] => One tw [1] => Three tes [2] => And yet another one )
但我确实需要这样:
Array ( [0] => One two [1] => Three test [2] => And yet another one )
如何解决问题?
I want to split text by the letter-followed-by-period rule. So I do this:
$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/\w\./", $text);
print_r($splitted_text);
Then I get this:
Array ( [0] => One tw [1] => Three tes [2] => And yet another one )
But I do need it to be like this:
Array ( [0] => One two [1] => Three test [2] => And yet another one )
How to settle the matter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它在字母和句号上分开。如果您想进行测试以确保句点之前有一个字母,则需要使用正向查找后面断言。
Its splitting on the letter and the period. If you want to test to make sure that there is a letter preceding the period, you need to use a positive look behind assertion.
使用
explode
语句使用“.”更新
explode 语句还检查空格。
您可以使用任何类型的分隔符,也可以使用短语,而不仅仅是单个字符
use
explode
statementUpdate
using ". " the
explode
statement check also the space.You can use any kind of delimiters also a phrase non only a single char
使用正则表达式在这里有点大材小用,您可以轻松使用
explode
。由于已经给出了基于爆炸的答案,因此我将给出基于正则表达式的答案:使用的正则表达式:
\.\s*
\.
- 点是元字符。为了匹配字面匹配,我们对其进行转义。\s*
- 零个或多个空格。如果您使用正则表达式:
\.
,您将在创建的某些片段中包含一些前导空格。
Using regex is an overkill here, you can use
explode
easily. Since a explode based answer is already give, I'll give a regex based answer:Regex used:
\.\s*
\.
- A dot is a meta char. To match a literal match we escape it.\s*
- zero or more white space.If you use the regex:
\.
You'll have some leading spaces in some of the pieces created.