简体   繁体   English

PHP preg_replace SVG宽度和高度值

[英]PHP preg_replace SVG width and height values

Been having a little issue with my inline SVGs and would love some suggestions. 我的嵌入式SVG出现了一些问题,希望您提出一些建议。 I'm creating them in Illustrator so I've been running them through this filter I created to clean them up as well as allow them to be displayed 100% width to scale using the preserveAspectRatio and padding trick I read about: 我是在Illustrator中创建它们的,所以我一直通过创建该过滤器来运行它们,以清理它们,并允许它们使用我了解到的prepareAspectRatio和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);

This was working great I thought as I could now size the container responsively and the SVG scaled accordingly but then realized Firefox wasn't displaying anything at all although it was working fine in Chrome and Safari. 我认为这非常有效,因为我现在可以响应地调整容器的大小,并且SVG进行了相应的缩放,但随后意识到Firefox虽然在Chrome和Safari中运行良好,但根本不显示任何内容。

So in order to get this working I realized on Firefox if I removed the style attribute and change the svg width and height both to 100% I'm back to getting the desired results. 因此,为了使此工作正常进行,我在Firefox上意识到,如果我删除了style属性,并将svg的宽度和高度都更改为100%,我会返回所需的结果。 But I'm stumped on why I can't get preg_replace to work on my svg filter to replace the width and height. 但是我很困惑为什么我不能让preg_replace在我的svg过滤器上工作以替换宽度和高度。

Here is the revised code I've been attempting but can't get it to change the width and height attributes. 这是我一直在尝试的修改后的代码,但无法获取它来更改width和height属性。

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

Any suggestions would be greatly appreciated. 任何建议将不胜感激。 Cheers 干杯

Just got it to work with this preg_replace function 刚使其与此preg_replace函数一起使用

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

Always have trouble with preg_replace lol 总是遇到preg_replace大声笑

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

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