简体   繁体   English

如何使用preg_match获取“id或更多的html标题”?

[英]How to get “html title with id or more” using preg_match?

I am using 我在用

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

to get 要得到

<title>Exapmle</title>

How can I get this using preg_match? 如何使用preg_match获取此信息?

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

I am using this to get page title. 我用它来获取页面标题。 Maybe, a title can have more than 'id' 也许,一个标题可以超过'id'
While answering, please keep that in mind. 在回答时,请记住这一点。


Okey. 好。 Here is a complete code to get page title. 这是获取页面标题的完整代码。 Hope that it helps others. 希望它能帮助别人。

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

You can add (.*) which match any characters. 您可以添加(.*)匹配任何字符。 Note that last element of $title is your title 请注意, $title最后一个元素是您的标题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM