php-在处爆炸字符串.但忽略小数,例如2.9 [英] php - explode string at . but ignore decimal eg 2.9
问题描述
目前,我正在.
处分解一个字符串,它可以按我的喜好工作.唯一的问题是,当.
作为小数点出现时也会爆炸.有没有一种方法可以将decimal
点排除在爆炸功能之外?
Currently I am exploding a string at .
and it works as I like. the only issue is that is also explodes when the .
occurs as a decimal point. Is there a way of excluding decimal
points from the explode function?
我当前的设置:
如您所见,它在两个数字之间的.
处爆炸
My current setup:
As you can see it is exploding at .
between the two numbers
$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
)
推荐答案
您可以使用 preg_split
为此,使用/(?<!\d)\.(?!\d)/
的正则表达式:
You can use preg_split
for this with the regex of /(?<!\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)
- a "negative lookbehind" meaning it will only match if there is NO digit (\d
) before the dot\.
- a literal.
character. It needs to be escaped as.
in regex means "any character"(?!\d)
- a "negative lookahead" meaning it will only match if there is NO digit (\d
) after the dot
其他:
您可以通过使用正则表达式(/(?<!\d)\.(?!\d)\s*/
)来消除空格,该正则表达式也将与点后的任意数量的空格匹配,或者可以使用$NewString = array_map('trim', $NewString);
.
You can get rid of the spaces by using a regex as /(?<!\d)\.(?!\d)\s*/
that will also match any number of white-spaces after the dot, or alternatively you can use $NewString = array_map('trim', $NewString);
.
这篇关于php-在处爆炸字符串.但忽略小数,例如2.9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!