0

I have a question about preg_replace. I have the following HTML in WordPress:

<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">

I change it to the following:

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

with the following 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
        )
    )
);

I have the feeling I have written some serious slow code, and it can be done in a single preg_replace.

Chris85 mentioned the HTML parser, so I found this and got this so far:

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

include('simple_html_dom.php');

$html = file_get_html($html);

From here I COULD loop through all images and change the th attribute. But how do I put the new element were it came from?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
poashoas
  • 1,790
  • 2
  • 21
  • 44
  • 1
    It'd probably be cleaner, and more reliable to use a parser, not sure about performance. How slow is this code? – chris85 Aug 24 '15 at 20:35
  • I have no idea how to measure that, I am a beginner PHP-er. I'll edit my question now – poashoas Aug 24 '15 at 20:43

1 Answers1

1

you should better use DOM

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

and extract the attributes with it.

Bernhard
  • 1,852
  • 11
  • 19
  • thank you, something like mentioned here? http://stackoverflow.com/questions/11387748/change-tag-attribute-value-with-php-domdocument – poashoas Aug 24 '15 at 20:51
  • yes like in the answer of this posting. look the answer: http://stackoverflow.com/a/11387770/4401439 with the difference that you need to use $item->getAttribute instead of $item->setAttribute – Bernhard Aug 24 '15 at 20:53