D5145c421cd25af6fa577c15219add90

Extract and return the bits between the <title> and </title> tags of an html page.

<?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 !

73415a883aec7c0a7aada9c4cdb208b5

Christoffer

February 9, 2010, February 09, 2010 16:49, permalink

2 ratings. Login to rate!
<?php
function get_title($html_page)
{
  return preg_match('/<title>(.+?)</title>/i', $html_page, $match) ? $match[1] : 'No title';
}
?>
74002eeb5435bacbda9bf392756d5033

El Barto

July 11, 2010, July 11, 2010 15:14, permalink

No rating. Login to rate!

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';
}
?>
D6025f3a269555ed2b203e184ef14a72

Tim Gallagher

July 14, 2010, July 14, 2010 04:49, permalink

No rating. Login to rate!

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

?>

Your refactoring





Format Copy from initial code

or Cancel