0

目前我正在爆炸一个字符串,.它可以按我喜欢的方式工作。唯一的问题是当.作为小数点出现时也会爆炸。有没有办法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 
)
4

2 回答 2

8

您可以使用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
)

演示

正则表达式是什么意思?

  • (?<!\d)- “负向后看”意味着只有\d在点之前没有数字 ( )时才会匹配
  • \.- 文字.字符。它需要被转义,因为.在正则表达式中意味着“任何字符”
  • (?!\d)\d- “负前瞻”意味着只有在点后没有数字 ( )时才会匹配

额外的:

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

于 2013-11-07T11:08:03.563 回答
0

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

$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
)
于 2013-11-07T11:06:52.057 回答