My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

PHP – Creating Dynamic Page Title From a Filename

In this tutorial, you will learn how to automatically create a page title from its filename in just a few lines of code in PHP.

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>