如何使用preg_match获得"html title with id or more"?



我正在使用

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];
}

您可以添加匹配任何字符的(.*)。请注意,$title的最后一个元素是您的标题

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

最新更新