doujie3888 2010-04-04 16:50
浏览 183
已采纳

使用preg_match_all()和结束字符匹配一个字符串中的多个项目

I have the following code:

preg_match_all('/(.*) \((\d+)\) - ([\d\.\d]+)[,?]/U',
    "E-Book What I Didn't Learn At School... (2) - 3525.01, FREE Intro DVD/Vid (1) - 0.15",
    $match);
var_dump($string, $match);

and get the following ouput:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(54) "E-Book What I Didn't Learn At School... (2) - 3525.01,"
  }
  [1]=>
  array(1) {
    [0]=>
    string(39) "E-Book What I Didn't Learn At School..."
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [3]=>
  array(1) {
    [0]=>
    string(7) "3525.01"
  }
}

which matches only one items... what i need is to get all items from such strings. when i've added "," sign to the end of the string - it worked fine. but that is non-sense in adding comma to each string. Any advice?

  • 写回答

1条回答 默认 最新

  • duandu1049 2010-04-04 16:54
    关注

    Try this regex:

    (.*?)\s*\((\d+)\)\s*-\s*(\d+\.\d+)(?:,\s*)?
    

    The major difference is that you had .* (greedy) which I replaced with .*? (un-greedy). Yours first "ate" the entire string (except line breaks) and then back tracked to match just one piece from your string.

    Demo:

    preg_match_all('/(.*?)\s*\((\d+)\)\s*-\s*(\d+\.\d+)(?:,\s*)?/',
        "E-Book What I Didn't Learn At School... (2) - 3525.01, FREE Intro DVD/Vid (1) - 0.15",
        $matches, PREG_SET_ORDER);
    print_r($matches);
    

    produces:

    Array
    (
        [0] => Array
            (
                [0] => E-Book What I Didn't Learn At School... (2) - 3525.01, 
                [1] => E-Book What I Didn't Learn At School...
                [2] => 2
                [3] => 3525.01
            )
    
        [1] => Array
            (
                [0] => FREE Intro DVD/Vid (1) - 0.15
                [1] => FREE Intro DVD/Vid
                [2] => 1
                [3] => 0.15
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端