2013-04-10 23 views
0

我有以下标签的多个实例的HTML页面中提取标签的最有效的方法:从多个字符串

<INCLUDEFILE-1-/var/somepath/file1.php> 
<INCLUDEFILE-2-/var/somepath/file2.php> 
<INCLUDEFILE-3-/var/somepath/file3.php> 
<INCLUDEFILE-4-/var/somepath/file4.php> 
<INCLUDEFILE-5-/var/somepath/file5.php> 

可以使用哪些代码提取所有上述的路径?我迄今得到了下面的代码,但不能让它正常工作:

preg_match_all('/INCLUDEFILE[^"]+/m', $html, $result, PREG_PATTERN_ORDER); 

for ($i = 0; $i < count($result[0]); $i++) 
{ 
    $includefile = $result[0][$i]; 
} 

我需要提取:

/var/somepath/file1.php 
/var/somepath/file2.php 
/var/somepath/file3.php 
/var/somepath/file4.php 
/var/somepath/file5.php 

任何人都可以看到明显的错误(S)?

+2

你真的是说'FILEINCLUDE'在你的正则表达式,而不是'INCLUDEFILE' – 2013-04-10 18:44:52

+0

?感谢罗伯特指出了这一点......我会纠正和澄清 – Alex 2013-04-10 18:48:39

回答

0

你可以这样来做:

$html = ' 
    <INCLUDEFILE-1-/var/somepath/file1.php>fadsf 
    asdfasf<INCLUDEFILE-2-/var/somepath/file2.php>adsfaf 
    <INCLUDEFILE-3-/var/somepath/file3.php>asdfadsf 
    <INCLUDEFILE-4-/var/somepath/file4.php> 
    <INCLUDEFILE-5-/var/somepath/file5.php> 
'; 

$lines = explode(PHP_EOL, $html); 
$files = array(); 

foreach($lines as $line) 
{ 
    preg_match('/<INCLUDEFILE-\d+-(.+?)>/', $line, $match); 
    if(!empty($match)) { 
     $files[] = $match[1]; 
    } 
} 

var_dump($files); 
+0

将它们放在数组中会很好,但是因为它们可能因页面而异,所以我正在寻找一个更灵活的方法...答案可能在使用你的preg_match我会尝试! – Alex 2013-04-10 18:58:43

1

我稍微改变了你的正则表达式,并添加括号来捕捉你所需要的子模式。我没有在发布的例子中看到引号(“),所以我改为检查”>“来检测结束。我还添加了ungreedy修饰符,你可以尝试它是如何使用或不使用ungreedy。 [1]其中将包含第一个子模式匹配

preg_match_all('/<INCLUDEFILE-[0-9]+-([^>]+)>/Um', $html, $result, PREG_PATTERN_ORDER); 

for ($i = 0; $i < count($result[1]); $i++) 
{ 
    $includefile = $result[1][$i]; 
} 
+0

(+1)为m修饰符 – 2013-06-13 00:55:11

2

的捷径就能幸福。

$pattern = '`<INCLUDEFILE-\d+-\K/[^>\s]+`'; 
preg_match_all($pattern, $subject, $results); 
$results=$results[0]; 
print_r($results);