2013-06-23 38 views
0

我正在使用脚本获取第一张图像。Php在链接中获取图像名称

这是脚本。

$first_img = ''; 
       $my1content = $row['post_content']; 
       $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $my1content, $matches); 
       $first_img = $matches [1] [0]; 
       if(empty($first_img)){ //Defines a default image 
       $first_img = "/img/default.png"; 
       } 

该脚本回声完整的图像链接,例如: http://mywebsite.com/images/thisistheimage.jpg

可以将图像链接,图像名称和图像extenction ,所以我需要得到3个结果

链接,例如:http://mywebsite.com/images/ 图片名称,例如:thisistheimage 图片扩展,例如:.jpg

请让我知道,如果它清楚,谢谢阅读。

+2

不要使用正则表达式来解析HTML。 – Achrome

+0

你的正则表达式不正确。一个人喜欢的多个img会被吸引到一个单一的结果中。不要使用正则表达式来处理html,除非你知道你在做什么。改用DOM。 –

回答

0
<?php 
    $image_name  = pathinfo($first_img, PATHINFO_FILENAME); 
    $image_extension = pathinfo($first_img, PATHINFO_EXTENSION); 
    $image_with_extension = basename($first_img); 
    $image_directory  = dirname($first_img); 
?> 
0

查看内置的PHP功能pathinfo。看起来就是你所需要的。

+0

是否可以适应我的脚本? – AvinDE

+0

如果您需要更多详细信息,Mike W的上述答案更具描述性。 – GabeIsman

1

您可以使用内置的功能pathinfo()解析src你想要的东西。

$path_parts = pathinfo('/img/default.png'); 

echo $path_parts['dirname'], "\n";   // /img 
echo $path_parts['basename'], "\n";  // default.png 
echo $path_parts['extension'], "\n";  // .png 
echo $path_parts['filename'], "\n";  // default 

PHP的引用是here

+0

感谢您的帮助 – AvinDE