2013-06-23 36 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