0

How can i detect if there is some image html tag inside a text and extract just the url of the image ?

Eg.

Extract this url :

http://
www.someurl.com/somefileprocessor.php/12345/somedir/somesubdir/someniceimage.j
pg

from this tag (this tag can be inside another bunch of text and/or html)

<img title="Some nice title" border="0"
hspace="0" alt="some useful hint" src="http://
www.someurl.com/somefileprocessor.php/12345/somedir/somesubdir/someniceimage.j
pg" width="629" height="464" />

Thank's in advance Ângelo

1

3 Answers 3

2

A quick attempt at an <img/> tag specific regex:

preg_match_all('/<img[^>]*?\s+src\s*=\s*"([^"]+)"[^>]*?>/i', $str, $matches);

Example

Sign up to request clarification or add additional context in comments.

1 Comment

There should be at least one whitespace between img and src attribute. You should add a \s+. This fails: <img data-active-src="active.png" src="standard.png">
1

You can use CRUL to get content and then extract all img tags from content. to get data by curl:

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

then use regular expression to extract data.

^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$

this helps you to extract all image urls(in img tag or not).

If you need crawler ,you can use PHPCrawl

Comments

0

Thank's a lot for the awnswers, as i learn some more PHP. I try this quick and dirty way, it also extracts the image url

$imageurl    = strstr($title, 'src',FALSE);
$imageurl    = strstr($imageurl,'"',FALSE);
$imageurlpos = strpos($imageurl,'"');
$imageurl    = substr($imageurl,$imageurlpos+1);
$imageurlpos = strpos($imageurl,'"');
$imageurl    = substr($imageurl,0,$imageurlpos);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.