【问题标题】:preg_replace for images in PHPpreg_replace 用于 PHP 中的图像
【发布时间】:2015-11-18 09:40:04
【问题描述】:

我有一个关于 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="$1" data-img="$2{folder}$4"', // 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 $1 class="$2 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 属性。但是我怎么把新元素放在哪里来呢?

【问题讨论】:

  • 使用解析器可能会更干净,更可靠,但不确定性能。这段代码有多慢?
  • 我不知道如何衡量,我是 PHP 初学者。我现在将编辑我的问题

标签: php preg-replace


【解决方案1】:

你应该更好地使用 DOM

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

并用它提取属性。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-04-05
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 2010-09-29
  • 1970-01-01
相关资源
最近更新 更多