How to generate seo friendly url with php?

Member

by orpha , in category: PHP General , 2 months ago

How to generate seo friendly url with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 2 months ago

@orpha 

To generate an SEO friendly URL with PHP, you can follow these steps:

  1. Remove any special characters or spaces from the input string.
  2. Replace spaces with dashes (-) or underscores (_) to make the URLs more readable.
  3. Convert the string to lowercase to ensure consistency.
  4. Remove any extra slashes or unnecessary characters.
  5. Use the PHP function urlencode() to encode the URL and make it search engine friendly.


Here is an example code snippet to generate an SEO friendly URL in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function generateSEOUrl($url) {
    // Remove special characters
    $url = preg_replace('/[^a-zA-Z0-9s]/', '', $url);
    
    // Replace spaces with dashes
    $url = str_replace(' ', '-', $url);
    
    // Convert to lowercase
    $url = strtolower($url);
    
    // Remove extra slashes
    $url = rtrim(trim(trim($url), '/'), '/');
    
    // Encode the URL
    $url = urlencode($url);
    
    return $url;
}

// Usage
$inputString = "Generate SEO Friendly URL with PHP!";
$seoUrl = generateSEOUrl($inputString);
echo $seoUrl;


This code will take an input string, clean it up, and generate a SEO friendly URL that can be used in your website. You can modify the function to fit your specific requirements or add any additional rules for generating the URL.