Jump to content

preg_match_all problem


FutureWD

Recommended Posts

I want to show all the images from a website on one page with alt tags.

 

So this is what I have

preg_match_all("/<\s*img\s+[^>]*src\s*=\s*[\"']?([^\"' >]+)[\"' >]/isU", $FileSourceBody, $Url);

$UrlCount = count($Url[1]);
$alttag = 'get alt tags';

for($i = 0; $i < $UrlCount; $i++){

echo '<img src="'.$Url[1][$i].'" alt="'.$alttag.'"  /><br />';

}

 

I want that the preg_match_all gets the alt tags BUT when there is no alt tag, he still needs to show the image.

 

I hope one of you could help me

 

thanks in advance

Link to comment
Share on other sites

<?php

echo htmlentities($imgsrc = "<img src=\"final draft.jpg\" alt=\"My Final Draft\">\n<img src = ghoti.gif alt = fish>\n<img alt = biscuit src = recipe.png > <img src='taco_stand.bmp' />\n<img src='mild.jpg' alt='Mild Sauce'>\n\n");
preg_match_all('/<img\s+[^>]*?src\s*=\s*(["\'])?(.*?)(?(1)\1|(?=\s|\/?\>)).*?\>|<img[^>]*?\>/is', $imgsrc, $src_matches, PREG_SET_ORDER);
preg_match_all('/<img\s+[^>]*?alt\s*=\s*(["\'])?(.*?)(?(1)\1|(?=\s|\/?\>)).*?\>|<img[^>]*?\>/is', $imgsrc, $alt_matches, PREG_SET_ORDER);
foreach ($src_matches as $match => $value) echo htmlentities("$match: <IMG SRC=\"$value[2]\" ALT=\"{$alt_matches[$match][2]}\">\n");

?>

OUTPUT:

0: <IMG SRC="final draft.jpg" ALT="My Final Draft">
1: <IMG SRC="ghoti.gif" ALT="fish">
2: <IMG SRC="recipe.png" ALT="biscuit">
3: <IMG SRC="taco_stand.bmp" ALT="">
4: <IMG SRC="mild.jpg" ALT="Mild Sauce">

 

Try that.  I used two preg_match_all()s as to avoid (1) trying to match src and alt in different orders and (2) to simplify the case in which one is not present.  The arrays should always have corresponding offsets since if the first part of the regular expression does not match, the <img[^>]*?> will.

 

(Note that I escaped the ">" characters when they come after a question mark so they'd play nice with the code highlighting since the BB code parser interprets "?>" as the end of PHP code.  You may change the "\>" to ">" since they aren't necessary, but they shouldn't hurt anything either.)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.