Hi i am trying to make a seo friendly url using php. I am using the follwoing code to converting the url like exapmle.com/post/hi-how-are-you
and also using this .htaccess code
RewriteRule ^post/([w-]+)/?$ single_post.php?blog_title=$1 [L,QSA]
php slug url
function url_slug($str) {
$str = mb_strtolower(trim($str), 'UTF-8');
$str = preg_replace('/[[:^alnum:]]/iu', ' ', $str);
$str = trim($str);
$str = preg_replace('/s+/', '-', $str);
return $str;
}
But the problem is special character. For example: When i post some turkih character like (tırda bir öğün çok çıktı) the url looks like this
example.com/post/tırda-bir-öğün-çok-çıktı
Everything is ok for the slug but when i open the url i can not GETting any data with (tırda-bir-öğün-çok-çıktı).
What do I need to do in order to open URLs with special characters?
Do we have a chance to print all special characters in English? Like when i post something from data the url_slug can change the special character to english character for example:
tırda bir öğün çok çıktı
converted english character
tirda-bir-ogun-cok-cikti
2
Answers
Most common way is to use some mapping where you have non-latin letter as key and Latin letter representation:
Then you use replace:
Another way is using
iconv
function:w
matches word characters only where word char is[a-zA-Z0-9_]
and it doesn’t include all unicode characters.Change your rule to this:
[^/]+
will match any character that is not/
including unicode characters as well.You may also tweak php code a bit: