php - explode string at . but ignore decimal eg 2.9

后端 未结 2 479
南旧
南旧 2021-01-27 11:36

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

2条回答
  •  野性不改
    2021-01-27 12:12

    You can use preg_split for this with the regex of /(?:

    
    

    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?

    • (? - 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 /(? that will also match any number of white-spaces after the dot, or alternatively you can use $NewString = array_map('trim', $NewString);.

提交回复
热议问题