alt attr html image php

How can I automatically add the image “alt” attribute using image filename if it is missing, using php?

I need to add an image alt tag to hundreds of images. Problem is this would take forever and anyway there seems to be an easier solution.

I have been able to achieve this somewhat using javascript, as follows:

<script type="text/javascript">  
$(document).ready(function() {
var $img = $(this);
var filename = $img.attr('src')
if (typeof attr == typeof undefined || attr == false) {
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));

What this does is exactly what I want, so for example if I have this image:

<img src="" />

then the javascript will add the alt automatically like this:

<img src="" alt="the-image1" />

Well, that is all fine and dandy, but now I want to do it with PHP instead, because the problem is that this is only adding the tags into the front end which means it isn’t visible from page source (only inspect element), which means that the search engine won’t see the alt tag, which means that the only way to do it is to put it right into the page using php.

So how can I do my above javascript solution using php?