PHP视频swf正则表达式


php regular expression for video swf

我想从对象/嵌入HTML源获取视频url。我读到我可以用正则表达式来得到它但是我和正则表达式不是朋友

所以这是我所拥有的:

<?php 
function src($text) {
    $text = str_replace('"', '', $text);
    $text = str_replace('src=', '', $text);
    $temporary = explode('<embed', $text);
    $temporary = $temporary[1];
    $temporary = explode(' ', trim($temporary));
    return $temporary[0];
} 
$html = '
<object width="180" height="220">
    <param name="movie" value="http://www.domain.com/video/video1.swf"></param>
    <embed src="http://www.domain.com/video/video1.swf" type="application/x-shockwave-flash" width="180" height="220"></embed>
</object>
'; 
echo src($html);

这工作,但它是更好的正则表达式?

正则表达式更适合这种情况,因为src可能永远不会在第一个属性处,因此这将不起作用。

以下是我的建议:

function src($html) {
 if(preg_match('#<embed[^>]*?src=["''](.*?)["''](.*?)></embed>#si', stripslashes($html), $src)) {
  return $src[1];
 }
 return ''; // or any other error if you need
}
echo src($html);

将输出:http://www.domain.com/video/video1.swf

[^>]匹配不包含在括号内的单个字符。[^>]匹配除>以外的任何字符

["'']匹配src="src='

(.*?)点(.)表示匹配任何字符。*表示零次或多次。问号(?)表示贪婪,只要模式仍然匹配,就继续下去。总而言之,它意味着尝试匹配任何字符,0次或更多次,并获得尽可能多的

/i不区分大小写

这里有更多信息:

http://en.wikipedia.org/wiki/Regular_expression

http://www.regular-expressions.info/reference.html

为什么不使用DOM解析器呢?它被设计用来做这种工作。

$dom = new DOMDocument;
$dom->loadHTML($html);
$embed = $dom->getElementsByTagName('embed');
if ($embed->length) {
   $embed = $embed->item(0);
   if ($embed->hasAttribute('src')) {
       $src = $embed->getAttribute('src');
       // `$src` holds the `src` attribute of the `embed` element.  
   }
}

CodePad .