php - explode string at . but ignore decimal eg 2.9

核能气质少年 提交于 2019-12-04 05:39:39

问题


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 
)

回答1:


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);
?>

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
)

DEMO

What does the regex mean?

  • (?<!\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

Extra:

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);.




回答2:


If need to explode text like in your example, an easy way to do it is to explode ". " instead of ".".

$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
)


来源:https://stackoverflow.com/questions/19834288/php-explode-string-at-but-ignore-decimal-eg-2-9

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!