<?php
function get_title($html_page)
{
// split the page into 3 sections, with the <title> and </title> tags as delimiters.
$split_page = preg_split("%</?title[^>]*>%",$html_page);
if (sizeof($split_page) == 3)
return $split_page[1];
else
return "No title";
}
?>
Refactorings
No refactoring yet !
Christoffer
February 9, 2010, February 09, 2010 16:49, permalink
<?php
function get_title($html_page)
{
return preg_match('/<title>(.+?)</title>/i', $html_page, $match) ? $match[1] : 'No title';
}
?>
El Barto
July 11, 2010, July 11, 2010 15:14, permalink
Christoffer's code is great. Just to minor things:
- declare $match to avoid warnings on error_reporting = E_ALL environments (also because 'explicit is better than implicit')
- cosmetic changes to adjust to Zend's code style (a matter of personal opinion)
<?php
function getTitle($htmlPage)
{
$match = array();
return preg_match('/<title>(.+?)</title>/i', $htmlPage, $match) ? $match[1] : 'No title';
}
?>
Tim Gallagher
July 14, 2010, July 14, 2010 04:49, permalink
In my code, I needed to escape the forward slash in the closing title tag.
<?php
function getHtmlTitle( $htmlPage, $default = 'No Title' )
{
$match = array();
return preg_match( '/<title>(.+?)<\/title>/i', $htmlPage, $match) ? $match[1] : $default;
}
?>
Extract and return the bits between the <title> and </title> tags of an html page.