SEARCHING FOR A <IMG TAG WITHIN A HTML DOCUMENT

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sh33p1985
Forum Commoner
Posts: 78
Joined: Thu Mar 11, 2004 9:22 am

SEARCHING FOR A <IMG TAG WITHIN A HTML DOCUMENT

Post by sh33p1985 »

im writing a web based program to assess a webpage (structure,elements, syntax etc)

i need to search through the specified html file looking the for "<img tag".
output image tag found

if present, check to see wether it has the parameter "align=center".
output image aligned to center

store the src in a variable so i can check wether the image exists. eg. $src = "images/image.gif".

does anyone know how i could do this?
help would be much appreciated
deyna
TheBentinel.com
Forum Contributor
Posts: 282
Joined: Wed Mar 10, 2004 1:52 pm
Location: Columbus, Ohio

Re: SEARCHING FOR A <IMG TAG WITHIN A HTML DOCUMENT

Post by TheBentinel.com »

sh33p1985 wrote:i need to search through the specified html file looking the for "<img tag".
output image tag found

Code: Select all

$http = file_get_contents("http://www.thebentinel.com");
  // see if "<img" appears in the data
  $imgpos = strpos(strtolower($http), "<img");
  // if so, find its closing bracket
  if ($imgpos > 0)
  {
    print ("img found");
    $closeimgpos = strpos($http, ">", $imgpos);
    $tagtext = substr($http, $imgpos, $closeimgpos - $imgpos);
    // is "align=center" in that tag?
    $attrpos = strpos(strtolower($tagtext), "align=center");
    if ($attrpos > 0)
    {
      print ("align=center found");
    }
  }
No guarantees on the syntax, but that ought to get you moving in the right direction.

Hope it helps!
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

Possibly a bit of an overkill, but this will return the src='...' tag of every img tag:

Code: Select all

<?php
if (preg_match_all("/\<img.*\ssrc=.{2}?(\w{1}.+\w{1}).{2}?\s.*\>/ismU",$HTML,$matches))
{
   echo "image found";
   foreach($matches[1] as $value)
      echo $value."</br>";
}
?>
Post Reply