Php get image name in a link

946

i am using a script, to get the first image, inside a post.

Here is the script.

$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";
                }

This script echo the full image link, for example: http://mywebsite.com/images/thisistheimage.jpg

is possible to divide the image link , image name , and image extenction so i need to get 3 results

the link, example:http://mywebsite.com/images/ the image name, example: thisistheimage the image extenction, example: .jpg

Please let me know if its all clear, thanks for reading.

399

Answer

Solution:

You can use the built-in functionpathinfo() to parse thesrc for what you want.

$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

The PHP reference is here

121

Answer

Solution:

<?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 );
?>
904

Answer

Solution:

Check out the built-in PHP function pathinfo. Looks like just what you need.

People are also looking for solutions to the problem: php - $_GET and $_POST doesn't work

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.