tijmenamsing Posted February 20, 2012 Share Posted February 20, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/257411-set-max-width-to-all/ Share on other sites More sharing options...
KevinM1 Posted February 20, 2012 Share Posted February 20, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/257411-set-max-width-to-all/#findComment-1319332 Share on other sites More sharing options...
tijmenamsing Posted February 20, 2012 Author Share Posted February 20, 2012 Sir, you are brilliant. Hadn't even thought of this way. thanks! Quote Link to comment https://forums.phpfreaks.com/topic/257411-set-max-width-to-all/#findComment-1319343 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.