【问题标题】:Split string on dots not preceded by a digit without losing digit in split在不以数字开头的点上拆分字符串而不会丢失拆分中的数字
【发布时间】:2011-12-31 22:10:18
【问题描述】:

给定以下句子:

The is 10. way of doing this. And this is 43. street.

我希望 preg_split() 给出这个:

Array (
 [0] => "This is 10. way of doing this"
 [1] => "And this is 43. street"
)

我正在使用:

preg_split("/[^\d+]\./i", $sentence)

但这给了我:

Array (
 [0] => "This is 10. way of doing thi"
 [1] => "And this is 43. stree"
)

如您所见,每个句子的最后一个字符都被删除了。我知道为什么会发生这种情况,但我不知道如何防止它发生。有任何想法吗?前瞻和后瞻可以在这里提供帮助吗?我对这些不是很熟悉。

【问题讨论】:

    标签: php regex preg-split


    【解决方案1】:

    您想为此使用negative assertion

    preg_split("/(?<!\d)\./i",$sentence)
    

    不同之处在于[^\d]+ 将成为匹配的一部分,因此split 将删除它。 (?! 断言也被匹配,但是是“零宽度”,这意味着它不会成为分隔符匹配的一部分,因此不会被丢弃。

    【讨论】:

    • 你是对的。谢谢!看前面的字符是这里的意图。
    【解决方案2】:

    要在前面没有数字的文字点上爆炸你的字符串,匹配非数字,然后用\K(意思是“保留”从这里)重置完整字符串匹配,然后匹配“一次性”字符 - - 文字点和零个或多个空格。

    代码:(Demo)

    $string = 'The is 10. way of doing this. And this is 43. street.';
    var_export(
        preg_split('~\D\K\. *~', $string, 0, PREG_SPLIT_NO_EMPTY)
    );
    

    或 (Demo)

    var_export(
        preg_split('~(?<!\d)\. *~', $string, 0, PREG_SPLIT_NO_EMPTY)
    );
    

    或 (Demo)

    var_export(
        preg_split('~(?<=\D)\. *~', $string, 0, PREG_SPLIT_NO_EMPTY)
    );
    

    输出:(全部干净,没有尾随点,没有尾随空格,没有意外丢失的字符)

    array (
      0 => 'The is 10. way of doing this',
      1 => 'And this is 43. street',
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2017-04-15
      相关资源
      最近更新 更多