2012-08-05 86 views
1

我从一个字符串中提取文件,可以由用户输入或从读取页面源获取。Php解析字符串错误

我想提取所有的.jpg图片网址

所以,我使用(例如显示文本)以下,但一)它只返回第一个和b)它忽略掉名为.jpg

$word1='http://'; 
$word2='.jpg'; 

$contents = 'uuuuyyyyyhttp://image.jpgandagainhereitishttp://image2.jpgxxxxcccffff'; 

$between=substr($contents, strpos($contents, $word1), strpos($contents, $word2) - strpos($contents, $word1)); 

echo $between; 

有没有更好的方法来做到这一点?

在解析网页的情况下,我不能使用简单的DOM例如$images = $dom->getElementsByTagName('img');因为有时图像的引用是不是在标准标签

+0

当然,它只会返回第一个。你不检查字符串进一步匹配。这应该是(循环的)在一个循环中完成的,逐渐提高'开始'点来捕捉后面的比赛。 – 2012-08-05 00:56:43

+0

或者你可以使用正则表达式,http://php.net/manual/en/function.preg-match.php – Bryan 2012-08-05 01:01:47

回答

0

你可以做这样的事情:

<?php 

$contents = 'uuuuyyyyyhttp://image.jpgandagainhereitishttp://image2.jpgxxxxcccffff'; 

$matches = array(); 

preg_match_all('#(http://[^\s]*?\.jpg)#i',$matches); 

print_r($matches); 
0

你可以做到这一点使用preg_match_all(如前面回答),或者使用下面的函数。

它只是分解原始字符串,检查所有部分的有效链接并将其添加到数组中,然后返回。

function getJpgLinks($string) { 
    $return = array(); 
    foreach (explode('.jpg', $string) as $value) { 
     $position = strrpos($value, 'http://'); 
     if ($position !== false) { 
      $return[] = substr($value, $position) . '.jpg'; 
     } 
    } 
    return $return; 
}