How to generate SEO-friendly URLs with PHP?

Member

by susan , in category: SEO , a year ago

How to generate SEO-friendly URLs with PHP?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

by genevieve_boehm , a year ago

@susan 

To generate SEO-friendly URLs with PHP, you can follow these steps:

  1. Remove special characters, spaces, and replace them with hyphens
  2. Convert the URL to lowercase
  3. Trim repetitive hyphens and whitespaces
  4. Make sure the URL is unique and relevant to the content


Here is an example of a PHP function that generates SEO-friendly URLs:

1
2
3
4
5
6
function generate_seo_url($string){
    $string = preg_replace('/[^a-zA-Z0-9-_.]/', '-', $string);
    $string = strtolower(trim($string, '-'));
    $string = preg_replace('/-+/', '-', $string);
    return $string;
}


Note: This is just an example, you may need to modify the function to fit your specific needs.

Member

by hanna , 6 months ago

@susan 

Here's an updated version of the function that allows you to define custom URL separators and handle non-ASCII characters:


1 2 3 4 5 6 7 8 9 10 11 12 13


function generate_seo_url($string, $separator = '-'){ $transliteration_table = array( 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss', // Add more characters or their replacements as needed );

1
2
3
4
5
6
$string = str_replace(array_keys($transliteration_table), array_values($transliteration_table), $string);
$string = preg_replace('/[^a-zA-Z0-9-_.]/', $separator, $string);
$string = strtolower(trim($string, $separator));
$string = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $string);

return $string;


}


In this updated version, we added a transliteration table to handle non-ASCII characters. This table can be expanded to include additional character replacements. For example, 'ä' is replaced with 'ae', 'ö' with 'oe', 'ü' with 'ue', and 'ß' with 'ss'.


You can use this function to generate SEO-friendly URLs by passing a string to it. Optionally, you can specify a custom separator to use instead of the hyphen. For example:


1 2 3


$string = "Create SEO-friendly URLs with PHP"; $url = generate_seo_url($string); // "create-seo-friendly-urls-with-php"


In this example, the resulting URL is "create-seo-friendly-urls-with-php". The function removes spaces, converts the string to lowercase, and replaces non-alphanumeric characters with the specified separator.