PHP preg_replace SVG宽度和高度值

时间:2015-04-29 18:49:04

标签: php svg preg-replace

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

//$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);

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

1 个答案:

答案 0 :(得分:0)

刚刚使用这个preg_replace函数

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

始终遇到preg_replace lol

的问题