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

时间:2010-04-04 16:50:28

标签: php regex pcre

我有以下代码:

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

并获得以下输出:

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"
  }
}

只匹配一个项目...我需要的是从这些字符串中获取所有项目。当我在字符串的末尾添加“,”符号时 - 它运行正常。但是在为每个字符串添加逗号时没有意义。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

试试这个正则表达式:

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

主要区别在于你有.*(贪婪),我用.*?替换(非贪婪)。你首先“吃掉”整个字符串(除了换行符),然后回溯跟踪以匹配你的字符串中的一个字符串。

演示:

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

产生

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
        )

)