<?php

$root_dir = getcwd();
$image_directories = glob("{$root_dir}/*");
$file_name = "filename.txt";

foreach ($image_directories as $image_directory) :

        if(file_exists("{$image_directory}/{$file_name}")) :

                $data = file_get_contents("{$image_directory}/{$file_name}");

                $formatted_string = preg_replace_callback("#<table id=\"tablag\">(\s*(<tr>\s*(?:(?:<td>\s*<a[^>]+>.+?<\/a>\s*<\/td>\s*)+)<\/tr>\s*)+)<\/table>#i", "transform_table_html", $data);

                $formatted_string = preg_replace_callback("#(?<!<div class=\"col-md-4\">|<div class=\"col-md-4\">\n)<ul>\n?((?:<li>.+<\/li>\n?)+)<\/ul>#i", "transform_ul_html", $formatted_string );

                file_put_contents("{$image_directory}/{$file_name}", $formatted_string);

        endif;
        
endforeach;

function transform_table_html($matches)
{
        $result = $matches[0];

        if ( isset($matches[1]) ) :
                $extract_links = preg_replace("#<\/?t[rd]>|[\r\n]{2,}#i", "", $matches[1]);
                $result = preg_replace("#(<a[^>]*>.+?<\/a>)#i", "<div class=\"col-md-4\">\n<ul>\n<li>$1</li>\n</ul>\n</div>\n", $extract_links);
        endif;

        return $result;
}

function transform_ul_html($matches)
{
        $result = $matches[0];

                if ( isset($matches[1]) ) :
                        $result = preg_replace("#(<li>.+?<\/li>)#i", "<div class=\"col-md-4\">\n<ul>\n$1\n</ul>\n</div>\n", $matches[1]);
                endif;

        return $result;
}