[英]PHP preg_match regex (2)
大家好,我遇到了問題,我有以下代碼:
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0" width="320" height="240">
<param name="movie" value="http://www.domain.com" />
<param name="quality" value="high" />
<param name="wmode" value="opaque" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="FlashVars" value="file=http://www.domain.com/file.flv&screenfile=http://domain.com/file.jpg&dom=domain.com" />
<embed src="http://www.domain.com" width="320" height="240" bgcolor="#000000" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" flashvars="file=http://domain.com/file.flv&screenfile=http://domain.com/file.jpg&dom=domain.com" />
</object>
我需要在screenfile=
之后獲取該值,例如以下內容: http : screenfile=
,但是我不知道該怎么做,並且還需要替換寬度和高度屬性。
這是一個關於SO的常見問題,答案始終是相同的:正則表達式對於解析或處理HTML或XML來說是一個糟糕的選擇。 它們可以通過多種方式分解。 PHP至少具有三個內置的HTML解析器,它們將更加健壯。
看一下使用PHP和DOM解析HTML,並使用類似以下內容:
$html = new DomDocument;
$html->loadHTML($source);
$html->preserveWhiteSpace = false;
$params = $html->getElementsByTagName('param');
foreach ($params as $param) {
if ($param->getAttribute('name') == 'FlashVars') {
$params = decode_query_string($param->getAttribute('value'));
$screen_file = $params['screenfile'];
}
}
$embeds = $html->getElementsByTagName('embed');
$embed = $embed[0];
$embed->setAttribute('height', 300);
$embed->setAttribute('width', 400);
$raw_html = $html->saveHTML();
function decode_query_string($url) {
$parts = parse_url($url);
$query_string = $parts['query'];
$vars = explode('&', $query_string);
$ret = array();
foreach ($vars as $var) {
list($key, $value) = explode('=', $var, 2);
$ret[urldecode($key)][] = urldecode($value);
}
return $ret;
}
遵循以下原則:
$html = '<your HTML here>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//object/param[@name = "FlashVars"][1]/@value');
foreach ($result as $node) { // there should only be one
preg_match(/screnfile=([^&]+)/, $node->nodeValue, $matches);
print $matches[1];
}
未經測試,但您明白了。 我會盡量避免使用正則表達式來解析HTML,盡管在這種情況下,僅使用正則表達式是可行的(但是由於示例代碼和實際情況會有所不同,因此我仍然建議使用基於解析器的方法)。
使用/screenfile=([^&]+)/
查找screenfile的值。 $1
將包含所需的值。 使用regex解析html不是一個好主意。
更改寬度:
replace `/\bwidth="\d+"\b/` with width="423"
更改高度:
replace `/\bheight="\d+"\b/` with height="565"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.