preg_replace PHP 中的图像

preg_replace for images in PHP

我有一个关于 preg_replace 的问题。我在 WordPress 中有以下 HTML:

<img width="256" height="256" src="http://localhost/wp-content/uploads/2015/08/spiderman-avatar.png" class="attachment-post-thumbnail wp-post-image" alt="spiderman-avatar">

我改成如下:

<img src="" data-breakpoint="http://localhost/wp-content/uploads/2015/08/" data-img="theme-{folder}.jpg" class="srcbox" alt="spiderman-avatar">

与以下 preg_replace:

$html = preg_replace(
    '/src="(https?:\/\/.+\/)(.+\-)([0-9]+)(.jpg|.jpeg|.png|.gif)"/',
    'src="" data-breakpoint="" data-img="{folder}"', // Replace and split src attribute into two new attributes
    preg_replace(
        '/(width|height)="[0-9]*"/',
        '', // Remove width and height attributes
        preg_replace(
            '/<img ?([^>]*)class="([^"]*)"?/',
            '<img  class=" srcbox"', // Add class srcbox to class attribute
            $html
        )
    )
);

我感觉我写了一些非常慢的代码,并且可以在一个 preg_replace.

中完成

Chris85 提到了 HTML 解析器,所以我找到了这个并得到了这个:

http://nimishprabhu.com/top-10-best-usage-examples-php-simple-html-dom-parser.html

include('simple_html_dom.php');

$html = file_get_html($html);

从这里我可以遍历所有图像并更改 th 属性。但是我该如何放置新元素呢?

你最好使用 DOM

http://php.net/manual/de/domdocument.loadhtml.php

并用它提取属性。