dozabt4329 2018-05-24 13:14
浏览 237
已采纳

PHP或MySQL替换HTML启用的内容条目中的<img>标记

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!

  • 写回答

1条回答 默认 最新

  • dongmou1964 2018-05-24 13:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line