Reputation: 6812
For instance I have a string:
$string = '<div class="ImageRight" style="width:150px">';
which I want to transform into this:
$string = '<div class="ImageRight">';
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.
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
Reputation: 98921
Simple:
$string = preg_replace('/<div class="Image(.*?)".*?>/i', '<div class="Image$1">', $string);
Upvotes: 0
Reputation: 91430
How about:
$string = preg_replace('/(div class="Image.+?") style="width:.+?"/', "$1", $string);
Upvotes: 0
Reputation: 14149
I think this is what you're after...
$modifiedHtml = preg_replace('/<(div class="Image[^"]+") style="[^"]+">/i', '<$1>', $html);
Upvotes: 1
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
Reputation: 12508
Remove completely.
$string = preg_replace("/style=\"width:150px\"/", "", $string);
Replace:
$string = preg_replace("/style=\"width:150px\"/", "style=\"width:500px\"", $string);
Upvotes: 0