JustAnotherDev
JustAnotherDev

Reputation: 13

PHP or MySQL Replace for <img> tags in HTML enabled content entries

I’ve tags in following format spread all over my HTML enabled content entries:

<img alt="" src="{assets_2100:{filedir_12}HappyDog.jpg}" style="height:400px; width:100px">

I need to update all these in following format either via a PHP function before displaying at frontend or just update the MySQL once and for all:

<img alt="" src="/uploads/HappyDog.jpg" data-assetid="2100" data-filedir="12" data-filename="HappyDog.jpg" style="height:400px; width:100px”> 

The “/uploads/’ directory path is applicable for all images!

These tags were carried over when migrated content from EE

Edited: Okay, so far I tried the following as first step to remove the {filedir_X} from address:

    $parse_encoded = true;
    $pattern = ($parse_encoded)
        ? '/(?:{|&#123;)filedir_(\d+)(?:}|&#125;)/'
        : '/{filedir_(\d+)}/';
    if (preg_match_all($pattern, $htmlcontent, $matches, PREG_SET_ORDER))
    {
        foreach ($matches as $match){
            $htmlcontent = str_replace($match[0], '', $htmlcontent);
        }
    }

Then modified this to remove “{asset”, but ending up with “}” at the “src” attribute!

Upvotes: 0

Views: 126

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

Searching matches with preg_match_all to loop over results and to use str_replace is a waste of time. PHP has two functions for regex string replacements: preg_replace and preg_replace_callback (respectively for simple and complex replacements).

if ( $parseEncoded )
    $htmlContent = strtr($htmlContent, ['&#123;' => '{', '&#125;' => '}']);

$pattern = '~src=\K(["\']?){assets_(\d+):{filedir_(\d+)}([^}]+)}\1~i';
$replacement = '"/uploads/$4" data-assetid="$2" data-filedir="$3" data-filename="$4"';

$htmlContent = preg_replace($pattern, $replacement, $htmlContent);

Note that I changed the variable names: you have to choose between camelCase, snake_case and lowercase.

Upvotes: 1

Related Questions