SEO Friendly URL in PHP

Jan 17, 2022 1 minute read
Man in Black Shirt Holding Red Lighted Apple - by Emmanuel Ikwuegbu @ pexels.com

A simple URL structure is always a good way of building your SEO strategy. It is something like starting point of any content website. It starts since the beginning and will be with you forever (only ever when you are worried about moving URLs. Or codes like 301, 302 makes you unhappy).

Does a friendly article slug may help my SEO? It can be a tricky question to answer. Having SEO slug is just one of the factors that contribute to SEO score for a certain website. But as far as I know, Google does not care about it that much - as long as your URLs have valid structure. But one thing is for sure, your users will like it more than not.

Simple slug

This is the simplest example, it replaces all chars different than a-z, A-Z, 0-9 or space with dash -. It is a safe way of building SEO slug.

$txt = "Aloe Blacc - I Need A Dollar (Official Video)";
$txt = mb_strtolower($txt);
$txt = preg_replace("/[^A-Za-z0-9 ]/", '', $txt);
$txt = preg_replace("/[\s-]+/", "-", $txt);

echo $txt;
# result:
# aloe-blacc-i-need-a-dollar-official-video

Awesome slug

🎉 My favorite one, it replaces chars based on the mapping. It works nice, but you must remember to include in the mapping all chars you used in your headlines.

$txt =  "¿Aloe Blacc necesita 1$ o 1€ en España?";
$txt = mb_strtolower($txt);
$search =  ['¿', '$',    '€',    '?', 'ñ'];
$replace = ['-', '-usd', '-eur', '-', 'n'];
$txt = str_replace($search, $replace, $txt);
$txt = preg_replace("/[\s-]+/", "-", $txt);
$txt = trim($txt, "-");

echo $txt;
# result:
# aloe-blacc-necesita-1-usd-o-1-eur-en-espana

Summary

The URL structure can help you, or even more help your users. Be sure that you have checked that link, it is an official Google Search Docs. It will help you with building a proper URL structure.

 

Disclaimer: The opinions expressed here are my own and do not necessarily represent those of current or past employers.
Comments (0)