Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用preg_match_all()和结束字符匹配一个字符串中的多个项目_Php_Regex_Pcre - Fatal编程技术网

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

Php 使用preg_match_all()和结束字符匹配一个字符串中的多个项目,php,regex,pcre,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]=>

我有以下代码:

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"
  }
}
它只匹配一个项目。。。我需要的是从这些字符串中获取所有项。当我在字符串末尾添加“,”符号时,效果很好。但在每个字符串中添加逗号是没有意义的。有什么建议吗?

试试这个正则表达式:

(.*?)\s*\((\d+)\)\s*-\s*(\d+\.\d+)(?:,\s*)?
主要的区别是您有
*
(贪婪),我将其替换为
*?
(非贪婪)。你的第一个“吃”了整个弦(断线除外),然后回溯到只匹配你弦中的一段

演示:

产生:

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
        )

)

但是如何处理逗号呢?看看第二个item@nefo_x使用了
/U
修饰符,默认情况下,该修饰符使量词不贪婪。这就是为什么你不应该使用这个修饰语;它不可避免地造成的混乱超过了任何好处。如果你想要一个量词是非贪婪的,那就添加一个
@Alan,啊,我认为这与Unicode有关,但我想这是一个小写的
u
。谢谢
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
        )

)