Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create URL slugs for chinese characters. Using PHP

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.

like image 671
Kim Stacks Avatar asked Nov 04 '25 17:11

Kim Stacks


1 Answers

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)
like image 67
Ahosan Karim Asik Avatar answered Nov 07 '25 11:11

Ahosan Karim Asik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!