【问题标题】:php preg_replace help iframe srcphp preg_replace 帮助 iframe src
【发布时间】:2011-07-21 20:13:24
【问题描述】:

我创建了一个函数,它将为 youtube 嵌入代码设置高度、宽度和 wmode=transparent。现在 youtube 正在返回 iframe 代码。所以,我需要在 youtube src 的末尾附加“?wmode=transparent”。

例如。
原代码:

我希望将其替换为:

替换高度和宽度是有效的,但替换 src 不起作用。

我正在使用下面的正则表达式

$patterns[] = '/src="http:\/\/www.youtube.com\/embed\/[a-zA-Z0-9._-]"/';
$replacements[] = 'src="http://www.youtube.com/embed/${1}?wmode=transparent"';

下面是我的功能。

函数 SetHeightWidthVideo($markup,$w='200',$h='120') { //使其 wmode = 透明

  $markup = str_replace('<embed ','<embed wmode="transparent" ',$markup);
  //$w = '200';
  //$h = '120';

  $patterns = array();
  $replacements = array();
  if( !empty($w) )
  {
      $patterns[] = '/width="([0-9]+)"/';
      $patterns[] = '/width:([0-9]+)/';

      $replacements[] = 'width="'.$w.'"';
      $replacements[] = 'width:'.$w;
  }

  if( !empty($h) )
  {
      $patterns[] = '/height="([0-9]+)"/';
      $patterns[] = '/height:([0-9]+)/';

      $replacements[] = 'height="'.$h.'"';
      $replacements[] = 'height:'.$h;
  }



  $patterns[] = '/src="http:\/\/www\.youtube\.com\/embed\/[a-zA-Z0-9._-]"/';
  $replacements[] = 'src="http://www.youtube.com/embed/${1}?wmode=transparent"';

  return preg_replace($patterns, $replacements, $markup);

}

请帮忙。提前致谢。

【问题讨论】:

  • 您需要在 [a-zA-Z0-9._-] 表达式的末尾添加一个 +。现在它只能匹配一个字符。

标签: php regex preg-replace


【解决方案1】:

尝试:

$patterns[] = '/src="(.*?)"/';
$replacements[] = 'src="${1}?wmode=transparent"';

return preg_replace($patterns, $replacements, $markup);

【讨论】:

    【解决方案2】:

    复制、粘贴、运行:

    function setHeightWidthSrc($s, $width, $height)
    {
      return preg_replace(
        '@^<iframe\s*title="(.*)"\s*width="(.*)"\s*height="(.*)"\s*src="(.*?)"\s*(.*?)</iframe>$@s',
        '<iframe title="\1" width="' . $width . '" height="' . $height . '" src="\4?wmode=transparent" \5</iframe>',
        $s
      );
    }
    
    $original = '<iframe title="YouTube video player" 
      width="420" height="349" src="http://www.youtube.com/embed/aXNUL1-urg8" 
      frameborder="0" allowfullscreen=""></iframe>
    ';
    print "$original\n";
    print setHeightWidthSrc($original, 100, 100) . "\n";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 2011-06-21
      • 2011-03-10
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多