2012-04-15 113 views
1

我有以下字符串从字符串中获取字符串?爆炸?

<embed src='herp.com' width='240' height='180' allowscriptaccess='always' allowfullscreen='true' flashvars='volume=94&stretching=fill&file=http%3A%2F%2Fmedia.cdn.com%2FTHEMP%2Fflash%2Ffile.mp4&plugins=viral-1d'/> 

而且我希望得到http%3A%2F%2Fmedia.cdn.com%2FTHEMP%2Fflash%2Ffile.mp4&plugins=viral-1d出来。

我想通过=爆炸,然后抓住倒数第二个价值,但(如果他们的Flash变数变量的脚本将不再工作之后再添herp="blah"例子),这可能是容易出错,有没有任何其他办法对我需要的字符串进行语法修改要稍微强一点?

回答

1

此处适当的方法是使用正确的HTML解析库解析HTML,并从<embed>标记中提取flashvars属性。如果你只有其中一个,你可以使用正则表达式。

该表达式将检索flashvars属性,并将该值传递给parse_str()以检索所有查询字符串组件。 parse_str()将对其调用urldecode(),因此您不需要。

// Regex gets the entire flahsvars 
$pattern = "/<embed[^>]+flashvars='([^']+)'/"; 
preg_match($pattern, $embed, $matches); 

// $matches[1] now holds the full contents of `flashvars` 

// Then parse_str() on the result: 
$parts = array(); 
parse_str($matches[1], $parts); 
print_r($parts); 

// The part you want is in the file key: 
echo $parts['file']; 


Array 
(
    [volume] => 94 
    [stretching] => fill 
    [file] => http://media.cdn.com/THEMP/flash/file.mp4 
    [plugins] => viral-1d 
) 

中使用的正则表达式的解释:

/<embed[^>]+flashvars='([^']+)'/ 

它首先查找<embed后跟任意字符除了闭合>[^>]+)。捕获组flashvars=将查找所有字符,但不包括flashvars属性的结束报价,并将它们存储在第一个捕获组$matches[1]中。

0

有一种更好的方式来做到这一点,看看:

http://php.net/manual/en/function.parse-str.php

它解析URL的查询字符串。当然,你必须首先删除所有额外的内容。只需使用正则表达式提取查询字符串

+1

强烈建议您使用它的阵列PARAM虽然 - 保存 – ChrisK 2012-04-15 16:54:13

+0

事实上,这将很好地工作潜在的安全问题......我甚至都不需要删除多余的垃圾。 – Steven 2012-04-15 16:54:26

+0

你是什么意思的数组参数? – Steven 2012-04-15 16:54:59

2
$str = "<embed src='herp.com' width='240' height='180' allowscriptaccess='always' allowfullscreen='true' flashvars='volume=94&stretching=fill&file=http%3A%2F%2Fmedia.cdn.com%2FTHEMP%2Fflash%2Ffile.mp4&plugins=viral-1d'/>"; 

// figure out where the params begin (keep the starting quote) 
$strpos = strpos($str, "flashvars=") + strlen("flashvars="); 
$str = substr($str, $strpos); 

// get the quoting char 
$delimiter = $str[0]; 

// first match strtok returns is our param list 
$str = strtok($str, $delimiter); 

parse_str($str, $params); 

var_dump($params);