skip to Main Content

I need to create a SEO friendly string only from alphanumeric and characters of my native language. It is sinhala.

My expected string should be something like this:

$myString = "this-is-a-දහසක්-බාධක-දුක්-කම්කටොලු-මැදින්-ලෝකය-දිනන්නට-වෙර-දරන";

I am using a function to create the string like this. And that function is as follow:

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[s_]/", "-", $string);
    return $string;
}

This function only works for English characters and output of above string as below:

$title = seoUrl("this-is-a-දහසක්-බාධක-දුක්-කම්කටොලු-මැදින්-ලෝකය-දිනන්නට-වෙර-දරන");
echo $title; // this-is-a-

Can anybody tell me how to modify above function to get all my characters (including my native language characters)

Hope somebody may help me out. Thank you.

2

Answers


  1. You use multibyte encoding. preg_replace doesn’t work with multibyte encoding. You should use mb_ereg_replace function

    Login or Signup to reply.
  2. Use /u flag for unicode and pL for letters, pN for numbers.

    Edit: due to some multibyte characters, mb_ereg_replace is the good choice:

    function seoUrl($string) {
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = mb_ereg_replace("[^x0D-x0Ews-]", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[s_]/", "-", $string);
        return $string;
    }
    $title = seoUrl("this-is-a-දහසක්-බාධක-දුක්-කම්කටොලු-මැදින්-ලෝකය-දිනන්නට-වෙර-දරන");
    echo $title;
    

    Output:

    this-is-a-දහසක්-බාධක-දුක්-කම්කටොලු-මැදින්-ලෝකය-දිනන්නට-වෙර-දරන
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search