I am beginner php developer. This is my first post here.
I have dynamic content and I need add alt tag for all my images (if not exists).
I have this code:
$content = 'Lorem ipsum dolor sit amet, <img src="https://www.name.com.pl/assets/images/about/4.jpg"> consectetur adipisicing <b>elit.</b> Dolores ducimus eius sint veritatis.
<img src="https://www.name.com.pl/upload/DZ_AREA_ATTRACTION/thumbs10/491cf6db24dc40325250fdeeac3157fa.jpg"> At, doloribus dolorum earum enim fugiat in, ipsa odit optio perspiciatis quibusdam quis sunt unde ut voluptas.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores ducimus eius sint veritatis. <img src="https://www.name.com.pl/upload/DZ_AREA_ATTRACTION/bfcbae278cabee99756d275b68603279.jpg" alt="abc"> At, <u>doloribus</u> dolorum earum enim fugiat in, ipsa odit optio perspiciatis <img src="https://www.name.com.pl/upload/DZ_AREA_ATTRACTION/b65cf0990317814f636b38ec7efe574b.jpg"> quibusdam quis sunt unde ut voluptas.';
$content = html_entity_decode($_POST['content']);
$title = $_POST['title'];
$pattern = '#<img(?!.*alt=")(.+src="(([^"]+/)?(.+)\..+)"[^ /]*)( ?\/?)>#i';
$content = preg_replace($pattern, "<img$1 alt=\"qqqqq\">", $content);
$content1 = strip_tags($content, '<img>');
//echo $content1 . "<br/><br/><br/>";
It’s work fine. When I run this code, $content has alt tags (new – if not exist, exist – when is available in string).
I need change this code to get dynamic alt.
When I change this line from:
$content = preg_replace($pattern, "<img$1 alt=\"qqqqq\">", $content);
to:
$content = preg_replace($pattern, "<img$1 alt=\"$title\">", $content);
this is not working 🙁 Alt is not adding. How can I repair it?
Please help me
>Solution :
You can use this code
$content = html_entity_decode($_POST['content']);
$title = "Your dynamic alt text"; // Replace this with your dynamic alt text retrieval logic
$pattern = '#<img(?!.*alt=")(.+src="(([^"]+/)?(.+)\..+)"[^ /]*)( ?\/?)>#i';
$content = preg_replace($pattern, "<img$1 alt=\"$title\">", $content);
$content1 = strip_tags($content, '<img>');
echo $content1;