PHP Program to Convert Title to URL Slug
Last Updated :
24 Oct, 2023
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
- First, we will convert the string to lower case.
- Replace the spaces with hyphens.
- Remove the special characters.
- Remove consecutive hyphens with single hyphen.
- Remove the starting and ending hyphens.
- Then Print the URL string.
Example:
PHP
<?php
function convertTitleToURL( $str ) {
$str = strtolower ( $str );
$str = str_replace ( ' ' , '-' , $str );
$str = preg_replace( '/[^a-z0-9\-]/' , '' , $str );
$str = preg_replace( '/-+/' , '-' , $str );
$str = trim( $str , '-' );
return $str ;
}
$str = "Welcome to GFG" ;
$slug = convertTitleToURL( $str );
echo $slug ;
?>
|
Using Regular Expression (preg_replace() Method)
- First, we will convert the string to lower case.
- Use the regular expression to replace the white spaces and special characters with hyphens.
- Remove the starting and ending hyphens.
- Then Print the URL string.
Example:
PHP
<?php
function convertTitleToURL( $str ) {
$str = strtolower ( $str );
$str = preg_replace( '/[^a-z0-9]+/' , '-' , $str );
$str = trim( $str , '-' );
return $str ;
}
$str = "Welcome to GFG" ;
$slug = convertTitleToURL( $str );
echo $slug ;
?>
|
Using urlencode() Methods
- First, we will convert the string to lower case.
- Convert the string to URL code and replace the + symbols with hyphens ( – ).
- Then Print the URL string.
Example:
PHP
<?php
function convertTitleToURL( $str ) {
$str = strtolower ( $str );
$str = urlencode( $str );
$str = str_replace ( '+' , '-' , $str );
return $str ;
}
$str = "Welcome to GFG" ;
$slug = convertTitleToURL( $str );
echo $slug ;
?>
|
Share your thoughts in the comments
Please Login to comment...