简体   繁体   English

正则表达式替换 HTML 标记中的所有宽度和高度值

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

I got this RegEx from another post, but it doesn't fully function like it should.我从另一篇文章中得到了这个正则表达式,但它并没有像它应该的那样完全 function。

Here is the pattern: /(<[^>]+ (height|width)=)"[^"]*"/gi and replacement: $1"auto"这是模式: /(<[^>]+ (height|width)=)"[^"]*"/gi和替换: $1"auto"

Here is a typical replacement string: <p width="123" height="345"></p>这是一个典型的替换字符串: <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> .现在,我希望它返回<p width="auto" height="auto"></p> ,但它返回的是<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?你能帮我弄清楚如何替换 HTML 标记中的宽度和高度值吗? Oh, and I would really like it to work with small apostroph-signs as well (eg width='*' ).哦,我真的很希望它也可以与小撇号一起使用(例如width='*' )。

Thanks a lot!非常感谢!

Don't do this with regex.不要使用正则表达式执行此操作。 Use the DOM instead -- it's not very hard:改用 DOM —— 这并不难:

$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');简单地删除属性可能会更好 - 如果是这样,请执行$el->removeAttribute('width'); or the analogous operation on height .或对height的类似操作。

Please use an HTML parser and not a regular expression.请使用HTML 解析器而不是正则表达式。 Please?请?

$input = '<p width="123" height="345"></p>';
$doc = DOMDocument->loadHTML($input);

// ... make changes ...

$output = $doc->saveHTML();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM