【问题标题】:PHP codeigniter splitting string to array by regular expressionPHP codeigniter通过正则表达式将字符串拆分为数组
【发布时间】:2017-09-11 02:50:56
【问题描述】:

我有一个文本文件,想使用正则表达式将文本拆分为数组。但我是正则表达式的新手,不知道如何使用它。 文本文件格式基本是这样的:

0,"20"1,"100000050"25,"100000050"19,""11,"Masuda"12,"Jin"
I want to split them like:
0: 0,"20"
1: 1,"100000050"
2: 25,"100000050"
...

请帮忙!任何答案将不胜感激!

【问题讨论】:

    标签: php regex codeigniter


    【解决方案1】:

    使用 preg_split() 函数。它的操作与 split() 完全一样,只是接受正则表达式作为模式的输入参数。

    使用PREG_SPLIT_DELIM_CAPTURE 返回分隔符模式中的括号表达式。

    preg_split(
      '/([\d]+,\"[0-9a-zA-Z]+\")/',
      $str,
      -1,
      PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
    );
    

    /([\d]+,\"[0-9a-zA-Z]+\")/ 是正则表达式。

    / = start or end of pattern string
    [ ... ] = grouping of characters
    \d - digits
    + = one or more of the preceeding character or group
    , = the literal comma character
    \" = the literal quote character
    [0-9a-zA-Z] = numbers and letters
    

    【讨论】:

    • 我不知道为什么正则表达式无法正确处理以下文本:79-1,“新鲜鲈鱼(野生) L”。它总是想念
    【解决方案2】:

    这似乎是一种奇怪的格式,所以我可能会遗漏一些东西,但这应该可以:

    ([0-9]+,\"([0-9a-z ]+)?\")
    

    详情

    [0-9]+            match a digit one or more times (this seems to be an ID of sorts)
    ,                 match a literal comma
    \"([0-9a-z ]+)?\" match an alphanumeric character or a space one or more times, optionally (you have an empty string), between quotes
    i                 flag to make it case insensitive
    

    将其与preg_match_all() 配对以获取数组中的所有匹配项:

    <?php
    $string = '0,"20"1,"100000050"25,"100000050"19,""11,"Masuda"12,"Jin"';
    preg_match_all("/([0-9]+,\"([0-9a-z]+)?\")/i", $string, $m);
    var_dump($m);
    

    第一个数组会有你需要的。

    Demo

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多