php preg_replace help iframe src

2020-05-01 09:33发布

I have created a function which will set height, width and wmode=transparent for youtube embed codes. Now youtube is returning iframe code. So, I need to append "?wmode=transparent" at the end of youtube src.

For eg.
Original code :

<iframe title="YouTube video player" width="420" height="349" src="http://www.youtube.com/embed/aXNUL1-urg8" frameborder="0" allowfullscreen=""></iframe>

I want it to be replaced with :

<iframe title="YouTube video player" width=" mywidth" height=" myheight" src="http://www.youtube.com/embed/aXNUL1-urg8 ?wmode=transparent" frameborder="0" allowfullscreen=""></iframe>

Replacing height and width is working, but replacing src does not work.

I am using below regex

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

Below is my function.

function SetHeightWidthVideo($markup,$w='200',$h='120') { //to make it wmode = transparent

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

}

Please help. Thanks in advance.

2条回答
闹够了就滚
2楼-- · 2020-05-01 09:44

copy, paste, run:

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";
查看更多
我只想做你的唯一
3楼-- · 2020-05-01 09:47

try:

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

return preg_replace($patterns, $replacements, $markup);
查看更多
登录 后发表回答