替换 iframe 的字符串值



我有这样的字符串

$string = ' <iframe width="560px" height="250px" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBdVKAGo41VFI44444440l17aXhg&q=Space+Needle,Seattle+WA" allowfullscreen></iframe>';

我需要新的字符串来替换数据属性,如下所示

$newstring = '<iframe width="100%" height="100%" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBdVKAGo41VFI44444440l17aXhg&q=Space+Needle,Seattle+WA" allowfullscreen></iframe>';

我不知道数据属性的价值,但我知道它将永远是 100%

怎么做?

你可以尝试php Preg_replace它用于使用正则表达式替换字符串部分

$string = preg_replace("/"([0-9]*)px"/si","'100%'",$string);
echo $string;

这也可以工作,但比preg_replace长:

$string = ' <iframe width="560px" height="250px"src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBdVKAGo41VFI44444440l17aXhg&q=Space+Needle,Seattle+WA" allowfullscreen></iframe>';
$pos = strpos($string, "src");
$newstring = substr_replace($string,' <iframe width="100%" height="100%" ',0,$pos);

使用preg_replace()你可以这样做

$string = ' <iframe width="560px" height="250px" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBdVKAGo41VFI44444440l17aXhg&q=Space+Needle,Seattle+WA" allowfullscreen></iframe>';
$s = preg_replace('/(width|height)="[0-9]*px"/', '$1="100%"', $string);
echo $s;

使用 (width|height) 可确保仅更改这两个属性。

结果:

<iframe width="100%" height="100%" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBdVKAGo41VFI44444440l17aXhg&q=Space+Needle,Seattle+WA" allowfullscreen></iframe>

如果你只想改变一个html元素的高度和宽度,你只需在你的html文档或php模板文件中包含一个好的旧css文件。不需要正则表达式或 dom 解析。

由于您的 iframe 看起来像是从 google 获得的,并且它没有类或 id,因此您可以将其放入div 或任何有 id 的东西中,以防页面中有其他 iframe。

div#maps-iframe-container iframe{
    width: 100%;
    height: 100%;
}

最新更新