开发者

RegEx replace all values of width and height in HTML-tags

开发者 https://www.devze.com 2023-03-12 07:36 出处:网络
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\"

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: <开发者_如何学JAVAp 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!


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号