Get HTML <title> with PHP

PHP:
$htmlSample = "djkfhksd <title>Titletext</title>dfgu dgyidfug";

function get_title($html) { 
  return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : ''; 
} 

echo get_title($htmlSample);
 
Thanks. I'm not sure I can do it that simply. I need to get the title for an include file that contains social sharing icons, and the title will be in a different format on every page. For example, on one page I have a ternary if statement:

PHP:
<title><?php echo (($subpage == "photos")?"Photos of ":"") . str_replace("<br />"," ",$title);?></title>

On another I have:

PHP:
<title><?php echo ucfirst($mainpage);?> Gallery</title>

...and some pages won't have any PHP in the title tags.

Please correct me if I'm wrong, I'm amazed I figured out some ternary statements.

Unless it's possible to do something like this and declare $title_tag on each page?

PHP:
<?php $title_tag = "<title>" . (($subpage== "photos")?"Photos of ":"") . str_replace("<br />"," ",$title); . "</title>"?>

For that I get the error: Parse error: syntax error, unexpected '.'
 
Last edited:
Back
Top Bottom