2012-08-05 120 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; 
}