【问题标题】:Splitting at string and keeping periods按字符串拆分并保持周期
【发布时间】:2015-10-29 02:53:49
【问题描述】:

我试图在 .!? 处拆分一个句子虽然保留它们,但由于某种原因它无法正常工作。我做错了什么?

$input = "hi i am1. hi i am2.";
$inputX = preg_split("~[.!?]+\K\b~", $input); 

print_r($inputX);

结果:

Array ( [0] => hi i am1. hi i am2. )

预期结果:

Array ( [0] => hi i am1. [1] => hi i am2. )

【问题讨论】:

  • 分割,分割字符,所以不要做一个完整的正则表达式。例如preg_split("~[.!?]~",。不过,这将删除 puntction。我会去preg_match_all("~(.*?[.!?])\s*~"..

标签: php regex preg-replace preg-split


【解决方案1】:

我不确定您是否需要 preg_split(),但如果可以,请尝试 preg_match_all()

$input = "hi i am1. hi i am2.";
preg_match_all("/[^\.\?\!]+[\.\!\?]/", $input,$matched);
print_r($matched);

给你:

Array
(
    [0] => Array
        (
            [0] => hi i am1.
            [1] =>  hi i am2.
        )
)

【讨论】:

  • 想到了,但如果 'am2' 没有句号,它就不起作用。只要有 .!?分隔文本。
  • [\.|\!|\?] 不会像您认为的那样做 - 它在字符类中包含 |。只需使用[.!?]
  • 我实际上从另一个答案中复制了它,以查看它是否按照 OP 的要求确定我是否应该回答,并忘记将其恢复为我最初打算使用的内容(没有| 字符)。我仍然习惯性地逃避.?之类的字符...
【解决方案2】:

尝试不使用\b,我认为这里是多余的(如果不是这样的话)。

$input = "hi i am1. hi i am2.?! hi i am2.?";
$inputX = preg_split("~(?>[.!?]+)\K(?!$)~", $input); 

print_r($inputX);

(?!$) 是为了避免在匹配的元素上拆分,如果它在字符串的末尾,那么不会有额外的空结果。原子分组?> 是为了避免在字符串末尾有一系列字符时拆分,例如?!.(如果没有原子分组,它将在! 上拆分,最后一个结果将是单个字符.)。输出:

Array
(
    [0] => hi i am1.
    [1] =>  hi i am2.?!
    [2] =>  hi i am2.?
)

【讨论】:

  • 完美。正是我需要的。 :)
  • 实际上,有没有办法让它不会在数字之间的时期分裂?所以 3.14 会保留为一个字符串,而不是 3 和 14?
  • @frosty try with (?!(?<=\d)[.!?]+\d)(?>([.!?]+))\K(?!$) 应该在数字之前或之后在字符上拆分,例如4..3,但不能在数字之间拆分,例如2.3
【解决方案3】:

我希望这是你所期待的

$input = "hi i am1. hi i !am?2."; // i have added other ?! symbols also

$inputX = preg_split("/(\.|\!|\?)/", $input,-1,PREG_SPLIT_DELIM_CAPTURE); 

print_r($inputX)

输出:

Array ( [0] => hi i am1 [1] => . [2] => hi i [3] => ! [4] => am [5] => ? [6] => 2 [7] => . [8] => )

【讨论】:

  • 我希望这符合您的要求
  • m 修饰符没有做任何事情。还有为什么不使用字符类?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 2021-01-19
  • 2018-04-18
  • 1970-01-01
  • 2016-11-26
  • 2022-11-03
相关资源
最近更新 更多