preg_match_all只返回第一个匹配项

时间:2014-10-30 14:14:51

标签: php regex

好的,基本上我试图浏览大量包含文件超链接的html代码。我使用preg_match_all查找所有出现的内容。但是,它永远不会返回预期的匹配数量。

拍摄HTML代码($ content的值):

<a class="file_download file_ext_docx" href="/download.php?f=/LiO2beoordeling%20door%20mentor%20Maartje%20ingevuld.docx">Download file 1.docx</a><br /><em>Some text<a class="file_download file_ext_docx" href="/download.php?f=/BP3/Referenties.docx">Download file 2.docx</a> </strong><br /><strong>- Some text: <a class="file_download file_ext_docx" href="/download.php?f=/Zelfevaluatie%204.2.docx">Download file 3.docx</a> Soem text: <a class="file_download file_ext_docx" href="/download.php?f=/BP3/sz-lio.docx">Download file 4</a> </strong><br /><a class="file_download file_ext_docx" href="/download.php?f=/BP3/poplio.docx">

PHP代码:

preg_match_all('/download\.php\?f=(.*?)">/', $content, $matches);
foreach($matches as $val){
    echo $val[0] ."<br />";
}

上面的代码只返回我的第一场比赛。奇怪的是,回应:

echo $val[1] ."<br />"; //Returns 2nd match
echo $val[2] ."<br />"; //Returns 3rd match
//etc

所以我想我应该只计算数组并​​将它包装在for循环中以解决这个问题。但是:

count($matches); //Returns 1

2 个答案:

答案 0 :(得分:2)

首先,你应该仔细阅读php.net文档http://php.net/manual/en/function.preg-match-all.php

但是在简历中,preg_match_all输入$匹配结果取决于你使用的标志:默认情况下PREG_PATTERN_ORDER所以$ matches数组应该是

  

对结果进行排序,以便$ matches [0]是一个完整模式的数组   匹配,$ matches [1]是由第一个匹配的字符串数组   带括号的子模式,依此类推。

在你的情况下:

Array
(
    [0] => Array
        (
            [0] => download.php?f=/LiO2beoordeling%20door%20mentor%20Maartje%20ingevuld.docx">
            [1] => download.php?f=/BP3/Referenties.docx">
            [2] => download.php?f=/Zelfevaluatie%204.2.docx">
            [3] => download.php?f=/BP3/sz-lio.docx">
            [4] => download.php?f=/BP3/poplio.docx">
        )

    [1] => Array
        (
            [0] => /LiO2beoordeling%20door%20mentor%20Maartje%20ingevuld.docx
            [1] => /BP3/Referenties.docx
            [2] => /Zelfevaluatie%204.2.docx
            [3] => /BP3/sz-lio.docx
            [4] => /BP3/poplio.docx
        )

)

因此,如果您想列出所有结果,您可以这样做

foreach($matches[0] as $val){
    echo $val ."<br />";
}

答案 1 :(得分:0)

你的模式是对的,但你看错了地方 当我转储你的结果时我发现它没问题:

array(2) {
  [0]=>
  array(5) {
    [0]=>
    string(75) "download.php?f=/LiO2beoordeling%20door%20mentor%20Maartje%20ingevuld.docx">"
    [1]=>
    string(38) "download.php?f=/BP3/Referenties.docx">"
    [2]=>
    string(42) "download.php?f=/Zelfevaluatie%204.2.docx">"
    [3]=>
    string(33) "download.php?f=/BP3/sz-lio.docx">"
    [4]=>
    string(33) "download.php?f=/BP3/poplio.docx">"
  }
  [1]=>
  array(5) {
    [0]=>
    string(58) "/LiO2beoordeling%20door%20mentor%20Maartje%20ingevuld.docx"
    [1]=>
    string(21) "/BP3/Referenties.docx"
    [2]=>
    string(25) "/Zelfevaluatie%204.2.docx"
    [3]=>
    string(16) "/BP3/sz-lio.docx"
    [4]=>
    string(16) "/BP3/poplio.docx"
  }
}
相关问题