How change content before page loads

I am using this function add alt tags. But only problem that it changes content after the page is loaded and you can see the text been changed. What do I need to change? I am new to php. Please be kind.

Thank you so much,

```
$content = '
replace alt <img src="aaaa" alt="" />
replace alt <img src="bbbb" alt=" " />
replace alt <img src="cccc" />
do nothing  <img src="dddd" alt="xxxxxxx" />
do nothing  <img src="eeee" alt="yyyyy" />

';

echo replace_alt($content, 'TEST');

function replace_alt($html_content, $alt_text='')
{   $count = preg_match_all('/<img[^>]+>/i', $html_content, $images);
    if($count>0)
    {   $o = $html_content;
        $t = 'alt="'.$alt_text.'" ';
        foreach($images[0] as $img)
        {   $is_alt = preg_match_all('/ alt="([^"]*)"/i', $img, $alt);
            if($is_alt==0)
            {   $new_img = str_replace('<img ', '<img '.$t , $img);
                $o = str_replace($img, $new_img, $o);
            }
            elseif($is_alt==1)
            {   $text = trim($alt[1][0]);
                if(empty($text))
                {   $new_img = str_replace(trim($alt[0][0]), $t, $img);
                    $o = str_replace($img, $new_img, $o);
                }
            }
        }
    }
    return $o;
}

```

That’s something geared more for JavaScript than PHP, Node.js or React depending on how sophisticated you want to make the script. Though the way way you are going about it is more complicated than it really should in PHP. I did something like that years ago with a dirty words replacement. I would look into something like str_ireplace function - https://www.php.net/manual/en/function.str-ireplace.php. You basically have the search and replace array setup at the top of your code. You just have to make them in more of usable format like $replace[‘xxxx’, ‘c c c’, ‘ddd’]; though to be honest I’m not exactly sure what you are after.

Sponsor our Newsletter | Privacy Policy | Terms of Service