skip to Main Content

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


  1. Most common way is to use some mapping where you have non-latin letter as key and Latin letter representation:

    $map = [
       'š' => 'sh',
       ...
    ];
    

    Then you use replace:

    str_replace(array_keys($map), array_values($map), $slug);
    

    Another way is using iconv function:

    iconv('UTF-8', 'ASCII//TRANSLIT', $slug);
    
    Login or Signup to reply.
  2. 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:

    RewriteRule ^post/([^/]+)/?$ single_post.php?blog_title=$1 [L,QSA]
    

    [^/]+ will match any character that is not / including unicode characters as well.

    You may also tweak php code a bit:

    function url_slug($str) {   
        $str = mb_strtolower(trim($str), 'UTF-8');
        $str = preg_replace('/[^pLpN]+/u', ' ', $str);
        $str = trim($str);
        $str = preg_replace('/h+/', '-', $str);
        return $str;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search