FutureWD Posted July 26, 2007 Share Posted July 26, 2007 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 Quote Link to comment Share on other sites More sharing options...
teng84 Posted July 26, 2007 Share Posted July 26, 2007 try to replace ? to + or {3,} for 3 or more character Quote Link to comment Share on other sites More sharing options...
Wildbug Posted July 30, 2007 Share Posted July 30, 2007 <?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.) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.