Open In App

PHP Program to Convert Title to URL Slug

In this article, we will see how to convert title sting to URL slug in PHP. URL strings are small letter strings concatenated with hyphens.

Examples:



Input: str = "Welcome to GFG"
Output: welcome-to-gfg

Input: str = How to Convert Title to URL Slug in PHP?
Output: how-to-convert-title-to-url-slug-in-php

There are three methods to convert a title to URL slug in PHP, these are:

Using str_replace() ans preg_replace() Methods

Example:




<?php
  
function convertTitleToURL($str) {
      
    // Convert string to lowercase
    $str = strtolower($str);
      
    // Replace the spaces with hyphens
    $str = str_replace(' ', '-', $str);
      
    // Remove the special characters
    $str = preg_replace('/[^a-z0-9\-]/', '', $str);
      
    // Remove the consecutive hyphens
    $str = preg_replace('/-+/', '-', $str);
      
    // Trim hyphens from the beginning
    // and ending of String
    $str = trim($str, '-');
      
    return $str;
}
  
$str = "Welcome to GFG";
$slug = convertTitleToURL($str);
  
echo $slug;
  
?>

Output
welcome-to-gfg

Using Regular Expression (preg_replace() Method)

Example:




<?php
  
function convertTitleToURL($str) {
      
    // Convert string to lowercase
    $str = strtolower($str);
      
    // Replace special characters 
    // and spaces with hyphens
    $str = preg_replace('/[^a-z0-9]+/', '-', $str);
      
    // Trim hyphens from the beginning
    // and ending of String
    $str = trim($str, '-');
      
    return $str;
}
  
$str = "Welcome to GFG";
$slug = convertTitleToURL($str);
  
echo $slug;
  
?>

Output
welcome-to-gfg

Using urlencode() Methods

Example:




<?php
  
function convertTitleToURL($str) {
      
    // Convert string to lowercase
    $str = strtolower($str);
      
    // Convert String into URL Code
    $str = urlencode($str);
      
    // Replace URL encode with hyphon
    $str = str_replace('+', '-', $str);
  
    return $str;
}
  
$str = "Welcome to GFG";
$slug = convertTitleToURL($str);
  
echo $slug;
  
?>

Output
welcome-to-gfg


Article Tags :