1

I am using

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

to get

<title>Exapmle</title>

How can I get this using preg_match?

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

I am using this to get page title. Maybe, a title can have more than '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];
}
Alper Güven
  • 329
  • 4
  • 15

1 Answers1

0

You can add (.*) which match any characters. Note that last element of $title is your title

preg_match("/\<title(.*)\>(.*)\<\/title\>/i",$str,$title);
B. Desai
  • 16,414
  • 5
  • 26
  • 47