joshis Posted November 6, 2009 Share Posted November 6, 2009 Hi, I would like to replace the img tags in my entire html string as the following way. 1. detect all img tags 2. if it has a height attribute, replace with my new value. 3. if it has a width attribute, replace with my new value. 4. add a link wraper for the new img tag 5. also add a div wraper to the new <a><img /> </a> element. My goal is to change all the large images to thumburl. Actually all the large images are surrounded by a anchor tag. I like to add that href to the new thumbnail link eg: <div class='thumb-wrap'><a href='mypage.php?id=4'><img width='500' height='200' src='image.jpg' /></a></div> to <div class='thumb-wrap'><a href='mypage.php?id=4'><img width='100' height='50' src='image.jpg' /></a></div> Can I write this using regex expression? Quote Link to comment https://forums.phpfreaks.com/topic/180565-replacing-image-tags/ Share on other sites More sharing options...
cags Posted November 6, 2009 Share Posted November 6, 2009 Probably not the best way of doing it, but something like this should manage most of what your after. Your descriptions of 4 and 5 got a little hazy especially with the example given at the end, but hopefully you'll get the idea. $width = 7; $height = 9; $input = "<div class='thumb-wrap'><a href='mypage.php?id=4'><img width='500' height='200' src='image.jpg' /></a></div>"; $pattern = array("~(<img.*?width=')(\d+)'~", "~(<img.*?height=')(\d+)'~", "~(<img[^>]*>)~"); $replace = array("\${1}{$width}'", "\${1}{$height}'", "<div><a href='blah'>$1</a></div>"); echo preg_replace($pattern, $replace, $input); Quote Link to comment https://forums.phpfreaks.com/topic/180565-replacing-image-tags/#findComment-952637 Share on other sites More sharing options...
joshis Posted November 6, 2009 Author Share Posted November 6, 2009 Sorry my steps mislead you, please ignore steps 4 and 5. The anchor and div tag should be there, around the img. We need to modify only the img tag, as example. Quote Link to comment https://forums.phpfreaks.com/topic/180565-replacing-image-tags/#findComment-952694 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.