【问题标题】:Split String into Text and Number将字符串拆分为文本和数字
【发布时间】:2012-12-30 03:48:20
【问题描述】:

我有一些可以采用以下格式的字符串

sometext moretext 01 文本 文本一些文本更多文本002 text text 1 (somemoretext) 等

我想将这些字符串拆分为:数字和数字之前的文本

例如:text text 1 (somemoretext)
当 split 将输出:
文本 = 文本文本
数字 = 1

数字之后的任何东西都可以丢弃

已阅读有关使用正则表达式的信息,并且可能使用 preg_match 或 preg_split,但在涉及正则表达式部分时我迷路了

【问题讨论】:

    标签: php regex preg-match preg-split


    【解决方案1】:
    preg_match('/[^\d]+/', $string, $textMatch);
    preg_match('/\d+/', $string, $numMatch);
    
    $text = $textMatch[0];
    $num = $numMatch[0];
    

    或者,您可以将preg_match_all 与捕获组一起使用,一次性完成所有操作:

    preg_match_all('/^([^\d]+)(\d+)/', $string, $match);
    
    $text = $match[1][0];
    $num = $match[2][0];
    

    【讨论】:

    • 感谢您的快速回答。没想到这么简单。
    • @user1981823 - 一旦你知道怎么做,一切都很容易;)
    • 值得注意的是,在您的示例中 A 两个输出仍然是数组,所以 $textMatch[0][0] = string 。您的链接也不再有效。
    • @Martin - 正确。那是个错误。固定。
    【解决方案2】:

    使用preg_match_all() + 如果你想匹配每一行使用m modifier:

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

    您所有的结果都在$matches 数组中,如下所示:

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

    输出示例:

    foreach ($matches[1] as $k => $text) {
        $int = $matches[2][$k];
        echo "$text => $int\n";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-30
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多