当前位置:编程学习 > asp >>

php - 如何使用 preg_replace 将表格宽度更改为 100%

如果宽度值以像素为单位,我想将 table 宽度更改为 100%。

我的意思是,如果表格宽度看起来像 width="500" 或 width="500px" ,那么我想将其替换为 100%.

我的意思是像这样 width="100%"。

谁能帮我做 preg_replace。

$content = 'holds all my html content';
$replace = '100%';
preg_replace($pattern,$replace,$content,-1);
有人可以帮我处理$pattern吗?

最佳答案

$string = '<table width=" 600 px "></table>' ;
$pattern = '/width=["\']\s*\d+\s*(px|%)\s*["\']/' ;
$own_style = 'width="100%"' ;
$new = preg_replace($pattern, $own_style, $string) ;
这可以帮助你,但如果你的 HTML 内容中没有更多的宽度属性。 否则,如果任何其他元素具有 with 属性,则它们的 width 将设置为 100%

因此,通常使用 REGEXP 来处理 HTML 是一种不好的做法。
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,