尝试替换PHP中的高度和宽度值

尝试替换PHP中的高度和宽度值,php,regex,preg-replace,Php,Regex,Preg Replace,试图用PHP替换字符串($content)中的height=”“和width=”“值,我尝试了preg replace,但没有成功, 还有关于我做错了什么的建议 样本内容为: $content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/c0sL6_DNAy0" frameborder="0" allowfullscreen></iframe>'; 在这里,我只是拿着火柴,寻

试图用PHP替换字符串($content)中的height=”“和width=”“值,我尝试了preg replace,但没有成功, 还有关于我做错了什么的建议

样本内容为:

$content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/c0sL6_DNAy0" frameborder="0" allowfullscreen></iframe>';
在这里,我只是拿着火柴,寻找我的身高和宽度

function _parseIt($match)
{
    $height = "height";
    $width = "width";

    if(substr($match, 0, 5) === $height){

        $pieces = explode("=", $match);
        $pieces[1] = "\"175\"";

        $new = implode("=", $pieces);
        return $new;

    } 

    if(substr($match, 0, 5) === $width){

        $pieces = explode("=", $match);
        $pieces[1] = "\"285\"";

        $new = implode("=", $pieces);
        return $new;

    }

    $new = $match;
    return $new;

}
可能有一种短得多的方法可以做到这一点,然而,我真的在6个月前才开始编程


提前谢谢

您可以使用
preg\u replace
。它可以包含一个要匹配的正则表达式数组和一个替换数组。您想要匹配
width=“\d+”
height=“\d+”
。(如果要解析任意html,则需要扩展正则表达式以匹配可选空格、单引号等。)


_parseIt()上的第3行应该是$height=“height”;好的,谢谢。如果(substr($match,0,5)==$height)应该反映($match,0,6),你可能需要详细说明。用什么替换什么?是否要删除高度=和宽度=数字,或添加或替换它们?--parseIt的解决方法相当复杂。你可以用一个
preg_replace('/(width | height)=“\d+”/”,“$1=”200“,$src)”来实现这一点。
我想取=”“中的任何数值,并用我自己的值替换它们……谢谢Mario,我走的方向绝对正确!非常好,正如你所说的那样。谢谢,我只希望有一天也能做到这一点。我需要用CSS%和px值来实现这一点。这在这样的价值观中起作用吗?
function _parseIt($match)
{
    $height = "height";
    $width = "width";

    if(substr($match, 0, 5) === $height){

        $pieces = explode("=", $match);
        $pieces[1] = "\"175\"";

        $new = implode("=", $pieces);
        return $new;

    } 

    if(substr($match, 0, 5) === $width){

        $pieces = explode("=", $match);
        $pieces[1] = "\"285\"";

        $new = implode("=", $pieces);
        return $new;

    }

    $new = $match;
    return $new;

}
$newWidth = 285;
$newHeight = 175;

$content = preg_replace(
   array('/width="\d+"/i', '/height="\d+"/i'),
   array(sprintf('width="%d"', $newWidth), sprintf('height="%d"', $newHeight)),
   $content);