【问题标题】:PHP preg_replace SVG width and height valuesPHP preg_replace SVG 宽度和高度值
【发布时间】:2015-07-09 05:33:46
【问题描述】:

我的内联 SVG 有点问题,希望得到一些建议。 我在 Illustrator 中创建它们,所以我一直在通过我创建的过滤器运行它们以清理它们,并允许它们显示 100% 宽度以使用我读到的 preserveAspectRatio 和填充技巧进行缩放:

//$svg_path variable contains the path to the svg code
$return_raw = file_get_contents($svg_path);
//Cleans out Illustrator extra jazz
fileContent = preg_replace('#<!--.*?-->#s', '', $return_raw);
$cleansed = preg_replace('#<(\w+)(?:\s+[^>]+)?>\s*</\1>#s', '', $fileContent);
$html = str_replace('<svg', '<svg style="width:100%; padding-bottom:92%; height:1px; overflow: visible" preserveAspectRatio="xMidYMin slice"', $cleansed);

我认为这很好用,因为我现在可以响应地调整容器大小,并且 SVG 也相应地缩放,但后来意识到 Firefox 根本没有显示任何内容,尽管它在 Chrome 和 Safari 中运行良好。

因此,为了让这项工作在 Firefox 上正常运行,我意识到如果我删除了 style 属性并将 svg 的宽度和高度都更改为 100%,我就会恢复到想要的结果。 但是我很困惑为什么我不能让 preg_replace 处理我的 svg 过滤器来替换宽度和高度。

这是我一直在尝试但无法更改宽度和高度属性的修改代码。

$return_raw = file_get_contents($svg_path);
//Cleans out Illustrator extra jazz
fileContent = preg_replace('#<!--.*?-->#s', '', $return_raw);
$cleansed = preg_replace('#<(\w+)(?:\s+[^>]+)?>\s*</\1>#s', '', $fileContent);
$svg = str_replace('<svg', '<svg preserveAspectRatio="xMidYMin slice"', $cleansed);

//Tried this
$svg_dimensions = preg_replace(array('/width="\d+"/i', '/height="\d+"/i'),array(sprintf('width="%d"', '100%'), sprintf('height="%d"', '100%')),$svg);

//And This
$svg_dimensions = preg_replace('/width="(\d+)"\s*height="(\d+)"/', 'width="100%" height="100%"', $svg);

任何建议将不胜感激。 干杯

【问题讨论】:

  • svg是xml格式,使用DOMDocument。

标签: php svg preg-replace


【解决方案1】:

刚刚让它与这个 preg_replace 函数一起工作

$svg_dimensions = preg_replace("/(width|height)=\".*?\"/","\${1}=\"100%\"", $svg );

preg_replace 总是有问题,哈哈

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 2013-11-26
    • 2016-06-15
    • 2011-12-22
    • 2016-08-02
    • 2022-01-15
    • 2016-09-11
    • 2017-12-26
    • 2013-04-06
    相关资源
    最近更新 更多