[英]Extract a particular part of a large HTML code block stored in PHP variable
我有一個類似下面的幻燈片的嵌入代碼。 這整個html存儲在$embed_code
變量中。
我正在用PHP打印此代碼。 現在,我需要此HTML字符串中的一段代碼。
代碼如下。 我只需要<object>
標記之間的代碼。
$embed_code = '
<div style="width:425px" id="__ss_617490"><strong style="display:block;
margin:12px 0 4px"><a href="http://www.slideshare.net/al.capone/funny-beer-babies-
enginnering-rev-2-presentation" title="Funny beer babies enginnering rev.
2">Funny beer babies enginnering rev. 2</a></strong>
<object id="__sse617490"
width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com
/swf/ssplayer2.swf?doc=becoming-an-engineer-1222340701618958-9&stripped_title=funny-
beer-babies-enginnering-rev-2-presentation&userName=al.capone" /><param
name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/>
<embed name="__sse617490" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=
becoming-an-engineer-1222340701618958-9&stripped_title=funny-beer-babies-enginnering-
rev-2-presentation& userName=al.capone" type="application/x-shockwave-flash"
allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed>
</object>
<div style="padding:5px 0 12px">View more<a href="http://www.slideshare.net
/"> presentations</a> from <a href="http://www.slideshare.net/al.capone">
al.capone</a>.</div></div>';
現在,我只希望從<object id="....." to "</embed> </object>
字符串,整個HTML都是動態生成的,因此請給我任何想法。
我怎樣才能做到這一點? 是否有任何PHP函數可以提取任何標簽之間的html?
我喜歡使用PHPQuery來使用PHP從HTML解析和提取數據。 它使用jQuery的簡單CSS樣式選擇器遍歷代碼。
因此它將是:
require('phpQuery/phpQuery.php');
$doc = phpQuery::newDocumentHTML($embed_code);
$div = pq('div#__ss_617490'); // select a DIV with the specified ID
var_dump($div->attr('style')); //To get the style attribute
var_dump($div->html()); // To get the inner html
// now to get the object tag like you desire.
$object_tag = pq('object');
// only get the first object
$object_tag = pq('object:first');
使用DOMDocument類。
$dom = new DomdDocument ();
$dom -> loadHtml ($embed_code);
$htmlObject = $dom -> getElementById ('__sse617490'); // Returns a DomElement
您可以只使用正則表達式來解析和提取它:
$embed_code = "blah blah <object ...>and other code here</object> blah blah";
$matches = array();
preg_match('#<object(\s*[^>])?>(.*)</object>#iU', $embed_code, $matches);
// $matches[0] = "<object ...>and other code here</object>"
// $matches[1] = "and other code here"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.