Jump to content

Recommended Posts

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?

 

Link to comment
https://forums.phpfreaks.com/topic/180565-replacing-image-tags/
Share on other sites

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);

Link to comment
https://forums.phpfreaks.com/topic/180565-replacing-image-tags/#findComment-952637
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.