Jump to content

Recommended Posts

Hi,

 

I have a page where users can add some text and additionally images. This is done through a textbox and NicEditor.

Users are able to add images with any size, by either uploading it or usea URL. The problem occurs when they add a image wider than 560px, because then it ruins my lay out.

This is why i want to add style="max-width:560px;" at the end of all image tags. So for example

<img src="http://images.com/image.jpg" style="max-width:560px;">

 

If made the following code but this only works when a user adds just one image, i need it to work also when there are multiple images.

 

<?php
$img = '<img src="http://images.com/image.jpg">';
$imgstart = strpos($img,'<img'); // get position of <img
if($imgpstart !== false) {
$imgend = strpos($img,'>'); // get position of >
$width = ' style="max-width:560px;">';
$img= substr_replace($img, $width, $imgend, 1);	// replace > with $width
}
echo $img;
?>

 

This may not be the safest and best solution so i'd like some help with a function which finds all images in a string and give them a max-width.

 

thanks!

Link to comment
https://forums.phpfreaks.com/topic/257411-set-max-width-to-all/
Share on other sites

Why not do this with straight CSS?

 

img {
   max-width: 560px;
}

 

Or, if that negatively affects other, non-user-supplied images, add a class to them and adjust accordingly (pseudo-code):

 

while($row = mysql_fetch_assoc($result)) {
   echo "<img src=\"{$row['img']}\" class=\"user-image\" />";
}

 

.user-image {
   max-width: 560px;
}

 

The point is that manipulating the DOM with PHP is almost always the bad way to go.  Setting an element's width is the job of CSS.  Add a rule to your external stylesheet (you are using an external CSS file, right?  Inline styles are a clear sign of doing it wrong ), and go from there.

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.