Reputation: 7256
I got this RegEx from another post, but it doesn't fully function like it should.
Here is the pattern: /(<[^>]+ (height|width)=)"[^"]*"/gi
and replacement: $1"auto"
Here is a typical replacement string:
<p width="123" height="345"></p>
Now, I would like this to return <p width="auto" height="auto"></p>
, but instead it returns <p width="123" height="auto"></p>
.
Could you help me figure out how you can replace both the width and height-values in an HTML-tag? Oh, and I would really like it to work with small apostroph-signs as well (e.g. width='*'
).
Thanks a lot!
Upvotes: 1
Views: 1639
Reputation: 359966
Please use an HTML parser and not a regular expression. Please?
$input = '<p width="123" height="345"></p>';
$doc = DOMDocument->loadHTML($input);
// ... make changes ...
$output = $doc->saveHTML();
Upvotes: 3
Reputation: 237995
Don't do this with regex. Use the DOM instead -- it's not very hard:
$dom = new DOMDocument;
$dom->loadHTML($yourHTML);
$xpath = new DOMXPath($dom);
$widthelements = $xpath->query('//*[@width]'); // get any elements with a width attribute
foreach ($widthelements as $el) {
$el->setAttribute('width', 'auto');
}
$heightelements = $xpath->query('//*[@height]'); // get any elements with a height attribute
foreach ($heightelements as $el) {
$el->setAttribute('height', 'auto');
}
$yourHTML = $dom->saveHTML();
It might be better simply to remove the attribute instead -- if so, do $el->removeAttribute('width');
or the analogous operation on height
.
Upvotes: 9