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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?