Creating a page title from its filename is easy in PHP. In this post I will show you how to do so in a few lines of code. The first line in the following code retrieves the file name. The next line checks whether there are any dashes in the name and replaces them with white spaces. Then the code checks to see if the file name is index, if so it assign ‘home’ to the title instead of index.
<?php // extract the filename $title = basename($_SERVER['SCRIPT_FILENAME'], '.php'); // replace dashes with whitespace $title = str_replace('_', ' ', $title); // check if the file is index, if so assign 'home' to the title instead of index if (strtolower($title) == 'index') { $title = 'home'; } // capitalize all words $title = ucwords($title);
Open your page in your text editor and include title.inc.php above the DOCTYPE:
<?php include('./includes/title.inc.php'); ?>
Then amend the title tag like this:
<title><?php $title ?></title>