title: Automatically adding width and height attributes to <img> tags with a PHP function
body: <p>What I want is a function I can run on user input that will intelligently find and add the <code>width</code> and <code>height</code> attributes to any <code>&lt;img&gt;</code> tag in a blob of HTML so as to avoid page-reflowing issues while images load.</p>
  
  <p>I am writing the posting script for a PHP forum, where a user's input is sanitised and generally made nicer before writing it to the database for later display. As an example of what I do to make things nicer, I have a script that inserts <code>alt</code> attributes into images like so:</p>
  
  <p><code>Here are two images: &lt;img src="http://example.com/image.png"&gt; &lt;img src="http://example.com/image2.png"&gt;</code></p>
  
  <p>which, upon sanitising by the posting script, becomes</p>
  
  <p><code>Here are two images: &lt;img src="http://example.com/image.png" alt="Posted image"&gt; &lt;img src="http://example.com/image2.png" alt="Posted image"&gt;</code></p>
  
  <p>(This makes it validate under HTML 4 strict, but maybe isn't in the spirit of the alt attribute—alas!)</p>
  
  <p>So, for my function, I have a vague idea that the server will need to run <code>getimagesize()</code> on each external image it finds in the block of HTML, then apply the attributes that function generates to each and every <code>&lt;img&gt;</code> tag it runs into. I assume that this function has been written before, but I have had no luck on Google or php.net docs. Do I have to start from scratch, or is somebody aware of a (relatively) robust function that I can use or adapt to do this job?</p>