Split String into Text and Number

后端 未结 2 1405
后悔当初
后悔当初 2020-12-03 23:33

I have some strings which can be in the following format

sometext moretext 01 text
text sometext moretext 002
text text 1 (somemoretext)
etc

I want to s

相关标签:
2条回答
  • 2020-12-03 23:51
    preg_match('/[^\d]+/', $string, $textMatch);
    preg_match('/\d+/', $string, $numMatch);
    
    $text = $textMatch[0];
    $num = $numMatch[0];
    

    Alternatively, you can use preg_match_all with capture groups to do it all in one shot:

    preg_match_all('/^([^\d]+)(\d+)/', $string, $match);
    
    $text = $match[1][0];
    $num = $match[2][0];
    
    0 讨论(0)
  • 2020-12-04 00:06

    Use preg_match_all() + if you wish to match every line use m modifier:

    $string = 'sometext moretext 01 text
    text sometext moretext 002
    text text 1 (somemoretext)
    etc';
    preg_match_all('~^(.*?)(\d+)~m', $string, $matches);
    

    All your results are in $matches array, which looks like this:

    Array
    (
        [0] => Array
            (
                [0] => sometext moretext 01
                [1] => text sometext moretext 002
                [2] => text text 1
            )
        [1] => Array
            (
                [0] => sometext moretext 
                [1] => text sometext moretext 
                [2] => text text 
            )
        [2] => Array
            (
                [0] => 01
                [1] => 002
                [2] => 1
            )
    )
    

    Output example:

    foreach ($matches[1] as $k => $text) {
        $int = $matches[2][$k];
        echo "$text => $int\n";
    }
    
    0 讨论(0)
提交回复
热议问题