2017-06-24 42 views
1

我使用如何使用preg_match獲得帶有id或更多id的html標題?

preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); 

得到

<title>Exapmle</title> 

我怎樣才能得到這個使用的preg_match?

<title id="ANY_ID">Exapmle</title> 

我正在使用它來獲取頁面標題。也許,一個標題可以超過'id'
在回答時,請記住這一點。


Okey。這是獲取頁面標題的完整代碼。希望它能幫助別人。

function get_title($url){ 
    $str = file_get_contents($url); 
    $str = trim(preg_replace('/\s+/', ' ', $str)); 
    // supports line breaks inside <title> 
    $match = preg_match("/\<title(.*)\>(.*)\<\/title\>/i",$str,$title); 
    // tries to catch if the title has an id or more 

    // if first prag_match gets an error 
    // (that means the title tag has no id or more) 
    // it tries to get title without id or more 
    if ($match === false) 
     { 
     preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); 
     } 

return $title[1]; 
} 

回答

0

您可以添加(.*)匹配任何字符。請注意,$title的最後一個元素是您的標題

preg_match("/\<title(.*)\>(.*)\<\/title\>/i",$str,$title);