Get HTML <title> with PHP

Associate
Joined
17 Apr 2006
Posts
549
Location
Staffordshire
I've used this code I found on Stack Overflow, but how would I actually echo the contents of the title tag?

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

I'm a PHP newbie, thanks for any help. :)
 
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:
are you trying to echo the code itself or the output of the code (like a user would see)?

In that final example I added I want to set the variable, so once the variable has the value I can echo the variable anywhere I need it.
 
Back
Top Bottom