如何按字母后按句点分割?

发布于 2024-08-24 17:09:13 字数 440 浏览 8 评论 0原文

我想按照字母后按句点的规则分割文本。所以我这样做:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

握住你手 2024-08-31 17:09:13

它在字母和句号上分开。如果您想进行测试以确保句点之前有一个字母,则需要使用正向查找后面断言。

$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/(?<=\w)\./", $text);
print_r($splitted_text);

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.

$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/(?<=\w)\./", $text);
print_r($splitted_text);
萌︼了一个春 2024-08-31 17:09:13

使用 explode 语句

$text = 'One two. Three test. And yet another one';
$splitted_text = explode(".", $text);
print_r($splitted_text);

使用“.”更新

$splitted_text = explode(". ", $text);

explode 语句还检查空格。

您可以使用任何类型的分隔符,也可以使用短语,而不仅仅是单个字符

use explode statement

$text = 'One two. Three test. And yet another one';
$splitted_text = explode(".", $text);
print_r($splitted_text);

Update

$splitted_text = explode(". ", $text);

using ". " the explode statement check also the space.

You can use any kind of delimiters also a phrase non only a single char

烟雨凡馨 2024-08-31 17:09:13

使用正则表达式在这里有点大材小用,您可以轻松使用 explode 。由于已经给出了基于爆炸的答案,因此我将给出基于正则表达式的答案:

$splitted_text = preg_split("/\.\s*/", $text);

使用的正则表达式:\.\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:

$splitted_text = preg_split("/\.\s*/", $text);

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文