create URL slugs for chinese characters. Using PHP

2019-03-31 20:44发布

问题:

My users sometimes use chinese characters for the title of their input.

My slugs are in the format of /stories/:id-:name where an example could be /stories/1-i-love-php.

How do I allow chinese characters?

I have googled and found the japanese version of this answer over here.

Don't quite understand Japanese, so I am asking about the chinese version.

Thank you.

回答1:

i have tested in Bengali characters

it may work. try this: at first the coded page (write code where in the page) have to convert into encoding type in UTF-8, then write code.

code here:

function to_slug($string, $separator = '-') {
    $re = "/(\\s|\\".$separator.")+/mu";
    $str = @trim($string);
    $subst = $separator;
    $result = preg_replace($re, $subst, $str);
    return $result;
}

$id=34;
$string_text="আড়াইহাজারে দেড় বছরের ---  শিশুর -গলায় ছুরি";
$base_url="http://example.com/";
echo $target_url=$base_url.$id."-". @to_slug($string_text);

var_dump($target_url);

output:

http://example.com/34-আড়াইহাজারে-দেড়-বছরের-শিশুর-গলায়-ছুরি

string 'http://example.com/34-আড়াইহাজারে-দেড়-বছরের-শিশুর-গলায়-ছুরি' (length=136)