Variable Visions

Building a Dynamic Title Tag with PHP

Published Thu. Jul. 11, 2024

A well-crafted title tag is a fundamental part of SEO and user experience. It tells search engines and users what a page is about, and it appears in browser tabs, search engine results, and social shares. But in dynamic websites, especially those powered by PHP, it's inefficient to hardcode every page's title. This is where generating dynamic title tags with PHP becomes useful.

In this article, we'll walk through how to build a flexible and dynamic title tag generator using PHP and preg_replace, a powerful regular expression tool for pattern-matching and text manipulation.

Why Use preg_replace?

You could easily use string concatenation or simple conditionals to set a title. But sometimes, your title needs smart adjustments—for example:

  • Stripping unwanted characters
  • Standardizing formatting
  • Replacing underscores or hyphens with spaces
  • Capitalizing words
  • Injecting brand names or keywords

This is where preg_replace shines, allowing you to transform strings based on regular expression patterns.

Example Use Case

Let's say you're building a content-driven website with pages generated from the URL slug. If your URL is:

https://example.com/articles/how-to-use-preg_replace

You might want the title tag to read:

How to Use preg_replace | MySite

Here's how to implement this in PHP.

Step-by-Step PHP Code

<?php
function generateTitleTag($slug, $siteName = 'MySite') {
    // 1. Remove file extension or query parameters
    $slug = preg_replace('/(\?.*)|(\.php$)/i', '', $slug);

    // 2. Extract last part of the slug (page name)
    $parts = explode('/', trim($slug, '/'));
    $page = end($parts);

    // 3. Replace hyphens and underscores with spaces
    $page = preg_replace('/[-_]+/', ' ', $page);

    // 4. Capitalize words
    $page = ucwords($page);

    // 5. Optional: Remove common filler words (e.g. "the", "a")
    $page = preg_replace('/\b(the|a|an)\b/i', '', $page);
    $page = preg_replace('/\s+/', ' ', $page); // Clean up extra spaces
    $page = trim($page);

    // 6. Assemble full title
    $title = $page . ' | ' . $siteName;

    return $title;
}

// Example usage
$currentUrl = $_SERVER['REQUEST_URI']; // Or hardcode a slug for testing
echo '<title>' . generateTitleTag($currentUrl) . '</title>';
?>

How It Works

Let's break down the key operations:

  1. Strip Extensions: We clean up .php extensions and query strings for cleaner titles.
  2. Extract Page Slug: We isolate the last segment of the URL path.
  3. Clean the Slug: Replace hyphens and underscores with spaces.
  4. Capitalize: Make each word uppercase for readability.
  5. Refine: Remove filler words and extra spaces.
  6. Compose: Append your site's name with a pipe divider.

Sample Output

URL Slug Title Tag
/about-us.php About Us | MySite
/services/web-design Web Design | MySite
/articles/how-to-use-preg_replace?ref=twitter How To Use Preg Replace | MySite

Final Thoughts

Using preg_replace in PHP lets you dynamically clean and format your title tags with elegance and control. While this is a relatively simple example, the same logic can be expanded to include metadata, breadcrumbs, or Open Graph tags.

Always test your regex and string manipulation on a variety of URL formats to ensure consistent behavior. With thoughtful structure, your PHP-powered website can maintain SEO-friendly and user-friendly titles automatically.

Keywords:SEO, PHP, preg_replace