2017-06-04 172 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'但是有些东西不正确 –