【问题标题】:php - explode string at . but ignore decimal eg 2.9php - 在 .但忽略小数,例如 2.9
【发布时间】:2025-11-23 13:20:04
【问题描述】:

目前我在. 爆炸了一个字符串,它可以按我喜欢的方式工作。唯一的问题是,当. 作为小数点出现时,它也会爆炸。有没有办法从爆炸功能中排除decimal 点?

我目前的设置: 如您所见,它在两个数字之间的. 处爆炸

$String = "This is a string.It will split at the previous point and the next one.Here 7.9 is a number";

$NewString = explode('.', $String);

print_r($NewString);

output

Array ( 
[0] => This is a string 
[1] => It will split at the previous point and the next one 
[2] => Here 7 
[3] => 9 is a number 
)

【问题讨论】:

    标签: php split explode


    【解决方案1】:

    您可以将preg_split/(?<!\d)\.(?!\d)/ 的正则表达式一起使用:

    <?php
        $String = "This is a string. It will split at the previous point and the next one. Here 7.9 is a number";
    
        $NewString = preg_split('/(?<!\d)\.(?!\d)/', $String);
    
        print_r($NewString);
    ?>
    

    输出

    Array
    (
        [0] => This is a string
        [1] =>  It will split at the previous point and the next one
        [2] =>  Here 7.9 is a number
    )
    

    DEMO

    正则表达式是什么意思?

    • (?&lt;!\d) - 一个“消极的后视”意味着它只会在点前没有数字 (\d) 时匹配
    • \. - 文字 . 字符。它需要被转义为. 在正则表达式中的意思是“任何字符”
    • (?!\d) - “负前瞻”意味着只有在点后没有数字 (\d) 时才会匹配

    额外:

    您可以通过将正则表达式用作/(?&lt;!\d)\.(?!\d)\s*/ 来消除空格,该正则表达式也将匹配点后的任意数量的空格,或者您也可以使用$NewString = array_map('trim', $NewString);

    【讨论】:

    • 非常感谢,我没有想到正则表达式,也感谢您的解释。
    【解决方案2】:

    如果需要像您的示例中那样爆炸文本,一个简单的方法是爆炸“。”而不是“。”。

    $String = "This is a string. It will split at the previous point and the next one. Here 7.9 is a number";
    
    $NewString = explode('. ', $String);
    
    print_r($NewString);
    
    output
    
    Array ( 
    [0] => This is a string 
    [1] => It will split at the previous point and the next one 
    [2] => Here 7.9 is a number
    )
    

    【讨论】: