Jump to content

Deleting stuff from html code with preg_replace


Zoltan

Recommended Posts

I'm a total noob when it comes to php so I'd like ask for help. :)

 

The mission is as follows:

 

I have my blog and I intend to post-process each post. I'd like to

find code pieces like this...

 

<a class="thickbox" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487">

<img id="thumb420" class="thumb" src="../wp-content/gallery/misc/thumbs/thumbs_someimage.jpg?340050829" alt="" width="160" height="88" /></a>

<a class="thickbox" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487"> </a>

 

(Blue highlights show parts which can/will change content and length.)

 

...and make them look like this:

 

<a class="shutterset_" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487">

<img id="thumb420" class="thumb" src="../wp-content/gallery/misc/thumbs/thumbs_someimage.jpg?340050829" alt="" width="160" height="88" /></a>

<a class="thickbox" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487"> </a>

 

So delete a bunch of stuff and replace the "thickbox" class with

"shutterset_". I was able to do the latter with the cunning use of

the str_replace() function, but the rest... I figured that

preg_replace() should be used for that but the docs on it are not

easy to digest. :)

 

I'd appreciate any pointers and advice.

 

EDIT: Another thing which boggles my mind is how to make the

algo work only in situations like above and not elsewhere.

For example it should ONLY delete that last line if it is right after a

a linked image of similar target.

try

<?php
$test = '<a class="thickbox" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487">
<img id="thumb420" class="thumb" src="../wp-content/gallery/misc/thumbs/thumbs_someimage.jpg?340050829" alt="" width="160" height="88" /></a>
<a class="thickbox" title="someimage.jpg" href="../wp-content/gallery/misc/someimage.jpg?820270487"> </a>';
$pattern = '/(="\.\.\/wp-content\/gallery\/[^\?]*)\?[^"]*/is';
$test =  preg_replace($pattern, '\1', $test);
$pattern = '/<a\s+class="thickbox"[^>]+>\s*<\/a>/';
$test = preg_replace($pattern, '', $test);
print_r($test );
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.