我的用户有时会使用中文字符作为他们输入的标题。
我的 slug 的格式为 /stories/:id-:name
,示例可以是 /stories/1-i-love-php
。
我如何允许使用中文字符?
我用谷歌搜索并在 here 上找到了这个答案的日文版本.
不太懂日文,所以问中文版。
谢谢。
最佳答案
我用孟加拉语字符测试过
它可能会起作用。试试这个: 首先编码页面(在页面的什么地方写代码)要转换成UTF-8的编码类型,然后写代码。
代码在这里:
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);
输出:
http://example.com/34-আড়াইহাজারে-দেড়-বছরের-শিশুর-গলায়-ছুরি
string 'http://example.com/34-আড়াইহাজারে-দেড়-বছরের-শিশুর-গলায়-ছুরি' (length=136)
关于php - 为中文字符创建 URL slugs。使用 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23238849/