Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex with dynamic name not change string

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading