gpt4 book ai didi

生成安全 URL 的 PHP 代码?

转载 作者:可可西里 更新时间:2023-11-01 13:34:00 25 4
gpt4 key购买 nike

我们需要根据一本书的标题生成一个唯一的 URL - 其中标题可以包含任何字符。我们如何搜索替换所有“无效”字符,以便生成有效且整洁的外观 URL?

例如:

"The Great Book of PHP"

www.mysite.com/book/12345/the-great-book-of-php

"The Greatest !@#$ Book of PHP"

www.mysite.com/book/12345/the-greatest-book-of-php

"Funny title "

www.mysite.com/book/12345/funny-title

最佳答案

啊啊啊啊

// This function expects the input to be UTF-8 encoded.
function slugify($text)
{
// Swap out Non "Letters" with a -
$text = preg_replace('/[^\\pL\d]+/u', '-', $text);

// Trim out extra -'s
$text = trim($text, '-');

// Convert letters that we have left to the closest ASCII representation
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

// Make text lowercase
$text = strtolower($text);

// Strip out anything we haven't been able to convert
$text = preg_replace('/[^-\w]+/', '', $text);

return $text;
}

这工作得很好,因为它首先使用每个字符的 unicode 属性来确定它是否是字母(或\d 对数字) - 然后它转换那些不是 - 的 - 然后它音译为ascii,对其他任何东西进行另一个替换,然后自行清理。 (Fabrik 的测试返回“arvizturo-tukorfurogep”)

我还倾向于添加停用词列表 - 以便从 slug 中删除这些停用词。 “the” “of” “or” “a” 等(但不要长篇大论,否则你会删除诸如“php”之类的东西)

关于生成安全 URL 的 PHP 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com