preg_split unexpected behavior

前端 未结 3 1452
囚心锁ツ
囚心锁ツ 2021-01-27 11:47

I use preg_split as the following:

I ex

相关标签:
3条回答
  • 2021-01-27 12:29

    You have to add delimiters to your regex like this:

    <?php
    
        $num = 99.14;
        $pat = "/[^a-zA-Z0-9]/";
              //^------------^Delmimiter here
        $segments = preg_split($pat, $num);
        print_r($segments);
    
    ?>
    

    Output:

    Array ( [0] => 99 [1] => 14 )
    

    EDIT:

    The question why OP got the entire string back in the array is simple! If you read the manual here: http://php.net/manual/en/function.preg-split.php

    And take a quick quote from there under notes:

    Tip If matching fails, an array with a single element containing the input string will be returned.

    0 讨论(0)
  • 2021-01-27 12:31

    You can also use T-Regx tool and you won't have such problems :)

    Delimiters are not required

    <?php
    $num = 99.14;
    $segments = pattern("[^a-zA-Z0-9]")->split($num);
    
    print_r($segments);
    
    0 讨论(0)
  • 2021-01-27 12:36

    If you only want to split along the decimal, you could also use:

    $array = explode('.', $num);
    
    0 讨论(0)
提交回复
热议问题