Weblurk
Weblurk

Reputation: 6812

Remove style attribute from certain HTML tags in a document and replace with class attribute

For instance I have a string:

$string = '<div class="ImageRight" style="width:150px">';

which I want to transform into this:

$string = '<div class="ImageRight">';
  1. I want to remove the portion style="width:150px with preg_replace() where the size 150 can vary, so the width can be 500px etc. aswell.

  2. Also, the last part of the classname varies aswell, so the class can be ImageRight, ImageLeft, ImageTop etc.

So, how can I remove the style attribute completely from a string with the above mentioned structure, where the only things that varies is the last portion of the classname and the width value?

EDIT: The ACTUAL string I have is an entire html document and I don't want to remove the style attribute from the entire html, only from the tags which match the string I've shown above.

Upvotes: 0

Views: 2110

Answers (5)

Pedro Lobito
Pedro Lobito

Reputation: 98921

Simple:

$string  = preg_replace('/<div class="Image(.*?)".*?>/i', '<div class="Image$1">', $string);

Upvotes: 0

Toto
Toto

Reputation: 91430

How about:

$string = preg_replace('/(div class="Image.+?") style="width:.+?"/', "$1", $string);

Upvotes: 0

James C
James C

Reputation: 14149

I think this is what you're after...

$modifiedHtml = preg_replace('/<(div class="Image[^"]+") style="[^"]+">/i', '<$1>', $html);

Upvotes: 1

SteeveDroz
SteeveDroz

Reputation: 6136

You can do it in two steps with

$place = 'Left';
$size = 500;
$string = preg_replace('/(?<=class="image)\W(?=")/',$place,$string);
$string = preg_replace('/(?<=style="width:)[0-9]+(?=")/',$size,$string);

Note: (?=...) is called a lookahead.

Upvotes: 0

Sujit Agarwal
Sujit Agarwal

Reputation: 12508

Remove completely.

$string = preg_replace("/style=\"width:150px\"/", "", $string);

Replace:

$string = preg_replace("/style=\"width:150px\"/", "style=\"width:500px\"", $string);

Upvotes: 0

Related Questions