2017-06-04 78 views
1

假設我們有串這樣的:PHP - 如何從許多IMG的src獲取所有的URL?

Its really great to <img src="image2.png" /> hear from you "Today is good <img src="http://www.google.com/picture2.png" /> day" Let's listen song together! ---------<img src="images/profile.png" />\\\\\\ 

這是整個字符串。我們有3 img裏面。

我們想從這個字符串產生變量像

output[0] = 'image2.png'; 
output[1] = 'http://www.google.com/picture2.png'; 
output[2] = 'images/profile.png'; 

我的意思是,我們有這個字符串,以及如何處理他從的img標籤提取所有的「SRC」並將其收集在一個新的數組變量。

怎麼辦?我們如何實現這一目標?

另外我使用CodeIgniter框架。也許可以用這個框架的方法來完成,但我不認爲這是可能的。

回答

1

使用preg_match_all()

$src = <<<EOL 
Its really great to <img src="image2.png" /> hear from you "Today is good 
<img src="http://www.google.com/picture2.png" /> day" Let's listen song 
together! ---------<img src="images/profile.png" />\\\\\\ 
EOL; 

preg_match_all('~src="([^"]+)~', $src, $matches); 

var_export($matches[1]); 
// output -> 
//  array (
//   0 => 'image2.png', 
//   1 => 'http://www.google.com/picture2.png', 
//   2 => 'images/profile.png', 
//  ) 

直播demo


更新:你可以在正則表達式模式中使用\K得到j UST是必要的$matches什麼:

preg_match_all('~src="\K[^"]+~', $src, $matches); 
var_export($matches); 
// output -> 
//  array (
//  0 => 
//  array (
//   0 => 'image2.png', 
//   1 => 'http://www.google.com/picture2.png', 
//   2 => 'images/profile.png', 
//  ), 
//  ) 

對於參考看到Escape sequences

+0

爲什麼'var_export($ matches [1]);'?爲什麼是1?爲什麼這會產生2行而不是1? –

+0

'$ matches [0]'包含匹配完整模式'src =「([^」] +)'的字符串數組。 '$ matches [1]'包含第一個子掩碼匹配數組:'([^「] +)' –

1

在整個頁面的源代碼中使用preg_match_all (string $pattern , string $subject [, array &$matches來挑選出src = values。就像這樣:

$src = array(); // array for src's 
preg_match_all ('/src="([^"]+)"/', $page_source, $src); 
$just_urls = $src [1]; 

哪裏$page_source是你的輸入和$src是導致src=值的數組,$just_urls是報價只是內部的陣列。

模式/src="([^"]+)"/將只返回引號內的內容。

請參見: https://secure.php.net/manual/en/function.preg-match-all.php

+1

這是不錯的,但不工作完全正確的。經過測試,看看這裏的結果:'https:// i.stack.imgur.com/oQFrL.png'。它給出了很好的結果和不好的結果,以及2行而不是1行。 –

+0

哦,你必須使用第二個數組進行匹配。我將編輯代碼。 –

0

您需要使用PHP DOM Extension。 DOM擴展允許您使用PHP通過DOM API對XML文檔進行操作。

你也可以在下面的代碼經過:

function fetchImages($content) { 
    $doc = new DOMDocument(); 
    $doc->loadHTML($content); 
    $imgElements = $doc->getElementsByTagName('img'); 

    $images = array(); 

    for($i = 0; $i < $imgElements->length; $i++) { 
     $images[] = $imgElements->item($i)->getAttribute('src'); 
    } 

    return $images; 
} 
$content = file_get_contents('http://www.example.com/'); 
$images = fetchImages($content); 

print_r($images); 
+0

很好。但我需要做的即時通訊PHP隊友:D –

+0

我可以知道確切的要求嗎?所以我可以進一步解釋:) –

+0

下面的答案完全按照我的意思產生結果。所有清晰,簡短,並在PHP中。這裏:'https:// i.stack.imgur.com/oQFrL.png'但是有些東西不正確 –