【问题标题】:Optimize regex replace in PHP优化 PHP 中的正则表达式替换
【发布时间】:2009-09-09 17:21:35
【问题描述】:

我编写了一个 PHP 函数来获取具有宽度和高度的视频嵌入代码,并允许您指定新的宽度。然后该函数将使用适当的比例因子缩小高度。我发现宽度和高度并不总是相邻的,所以我打了几个电话,我有预感是不必要的。有没有更好的方法来/清理执行以下操作?

function scale_video($video_embed,$new_width = 200){

    preg_match('/width="(\d)*"/', $video_embed, $width);
    preg_match('/height="(\d)*"/', $video_embed, $height);
    $width = substr($width[0],7,-1);
    $height = substr($height[0],8,-1);  

    $scale_factor = $new_width/$width;
    $new_height = floor($height * $scale_factor);

    $video_embed = preg_replace('/width="(\d)*"/','width="'.$new_width.'"',$video_embed);
    $video_embed = preg_replace('/height="(\d)*"/','height="'.$new_height.'"',$video_embed);

    return $video_embed;
}

【问题讨论】:

    标签: php regex string


    【解决方案1】:

    我唯一建议的是您的正则表达式模式需要改进。

    /width="(\d)*"/
    

    应该是:

    /width="(\d*)"/
    

    这将为您提供您正在寻找的整个值的组,而不是模式中每个字符的组。这样你就可以改变了:

    $width = substr($width[0],7,-1);
    

    进入

    $width = $width[1];
    

    您也可以轻松地将其应用于高度。通过将前两个参数转换为数组,可以将结束替换转换为一次调用。

    总的来说,我建议如下:

    function scale_video($video_embed,$new_width = 200){
    
        // only process if both matches have results
        if(preg_match('/width="(\d+)"/', $video_embed, $width) &&
          preg_match('/height="(\d+)"/', $video_embed, $height) {
    
            $width = $width[1];
            $height = $height[1];
    
            $scale_factor = $new_width/$width;
            $new_height = floor($height * $scale_factor);
    
            $video_embed = preg_replace(array('/width="(\d+)"/', '/height="(\d+)"/'), array('width="'.$new_width.'"', 'height="'.$new_height.'"'), $video_embed);
    
        }
    
        return $video_embed;
    }
    

    【讨论】:

      【解决方案2】:

      更好的方法可能是使用preg_replace_callback()/e modifier(用于“e评估代码”)进行设置,以便您只对每个模式进行一次正则表达式匹配,例如:

      $video_embed = preg_replace_callback('/width="(\d)*"/', 'scale_video_width_callback', $video_embed);
      
      function scale_video_width_callback($match) {
          // transform match and return transformed value
      }
      

      【讨论】:

        猜你喜欢
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-09
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多