-
How To Create A URL Slug With PHPtmp 2024. 1. 19. 09:45
Having a user friendly URL is user important not just for SEO but also to help the visitors know that the website they are on is correct. If you have spaces in your URL they will be replaced by %20 so if you are linking to the page.
http://www.example.com/this is the example demo page
The browser would actual render this URL as
http://www.example.com/this%20is%20the%20example%20demo%20page
As you can see this isn't the most user friendly URL so you need to be able to replace the spaces with hyphens. Here is a PHP snippet that will replace all spaces with a hyphen.
<?php function create_url_slug($string){ $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string); return $slug; } echo create_url_slug('this is the example demo page'); // This will return 'this-is-the-example-demo-page' ?>
Extended URL Slug Version
Here is an extended version of the URL slug function. This will take care of any characters which have accents and will also catch double hyphens in the URL and replace it will just the one hyphen.
function slugify($str) { $search = array('Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë'); $replace = array('s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E'); $str = str_ireplace($search, $replace, strtolower(trim($str))); $str = preg_replace('/[^\w\d\-\ ]/', '', $str); $str = str_replace(' ', '-', $str); return preg_replace('/\-{2,}', '-', $str); }
'tmp' 카테고리의 다른 글
Locust로 서버 성능 테스트하기 (1) 2024.02.28 allow_url_fopen 설정에 대한 자세한 설명 (0) 2024.02.20 Create A Weather Application With Google API Using PHP (1) 2024.01.19 Disable HTTP Cache With PHP (0) 2024.01.19 Store HTML View File In A Variable (0) 2024.01.19