我想清理 URL 中的字符串,所以这就是我基本上需要的:
例如。
This, is the URL!
必须返回
this-is-the-url
function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}
首先去除不需要的字符
$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
然后更改 unserscores 的空格
$url = preg_replace('/\s/', '-', $new_string);
最后编码即可使用
$new_url = urlencode($url);
OP 没有明确描述 slug 的所有属性,但这就是我从意图中收集的内容。
我对完美、有效、压缩的slug的解释与这篇文章一致:https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we% 20可以%20总结%20the,或%20end%20带有%20a%20连字符。
我发现之前发布的答案都没有能够一致地实现这一点(而且我什至没有扩展问题的范围以包括多字节字符)。
我推荐以下一行代码,它不需要声明一次性变量:
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
我的演示链接中未显示,这是更好地处理多字节字符串的尝试,尽管它不能完全适应卡西米尔的答案那么多的场景。
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower(iconv('utf-8', 'ascii//translit', $string))), '-');
我还准备了一个演示,突出显示我认为其他答案中的不准确之处。 (演示)
'This, is - - the URL!' input
'this-is-the-url' expected
'this-is-----the-url' SilentGhost
'this-is-the-url' mario
'This-is---the-URL' Rooneyl
'This-is-the-URL' AbhishekGoel
'This, is - - the URL!' HelloHack
'This, is - - the URL!' DenisMatafonov
'This,-is-----the-URL!' AdeelRazaAzeemi
'this-is-the-url' mickmackusa
---
'Mork & Mindy' input
'mork-mindy' expected
'mork--mindy' SilentGhost
'mork-mindy' mario
'Mork--Mindy' Rooneyl
'Mork-Mindy' AbhishekGoel
'Mork & Mindy' HelloHack
'Mork & Mindy' DenisMatafonov
'Mork-&-Mindy' AdeelRazaAzeemi
'mork-mindy' mickmackusa
---
'What the_underscore ?!?' input
'what-the-underscore' expected
'what-theunderscore' SilentGhost
'what-the_underscore' mario
'What-theunderscore-' Rooneyl
'What-theunderscore-' AbhishekGoel
'What the_underscore ?!?' HelloHack
'What the_underscore ?!?' DenisMatafonov
'What-the_underscore-?!?' AdeelRazaAzeemi
'what-the-underscore' mickmackusa
这将在 Unix shell 中完成(我刚刚在我的 MacOS 上尝试过):
$ tr -cs A-Za-z '-' < infile.txt > outfile.txt
我从一篇博客文章中得到了这个想法更多的壳,更少的鸡蛋
试试这个
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
用途:
echo clean('a|"bc!@£de^&$f g');
将输出:
abcdef-g
使用 intl transliterator 是一个不错的选择,因为有了它,您可以使用一组规则轻松处理复杂的情况。我添加了自定义规则来说明它如何灵活以及如何保留最大程度的有意义的信息。请随意删除它们并添加您自己的规则。
$strings = [
'This, is - - the URL!',
'Holmes & Yoyo',
'L’Œil de démon',
'How to win 1000€?',
'€, $ & other currency symbols',
'Und die Katze fraß alle mäuse.',
'Белите рози на София',
'പോണ്ടിച്ചേരി സൂര്യനു കീഴിൽ',
];
$rules = <<<'RULES'
# Transliteration
:: Any-Latin ; :: Latin-Ascii ;
# examples of custom replacements
'&' > ' and ' ;
[^0-9][01]? { € > ' euro' ; € > ' euros' ;
[^0-9][01]? { '$' > ' dollar' ; '$' > ' dollars' ;
:: Null ;
# slugify
[^[:alnum:]&[:ascii:]]+ > '-' ;
:: Lower ;
# trim
[$] { '-' > &Remove() ;
'-' } [$] > &Remove() ;
RULES;
$tsl = Transliterator::createFromRules($rules, Transliterator::FORWARD);
$results = array_map(fn($s) => $tsl->transliterate($s), $strings);
print_r($results);
不幸的是,PHP 手册中关于 ICU 转换的内容完全是空的,但您可以在这里找到有关它们的信息。
所有以前的 asnwers 都处理 url,但万一有人需要清理登录字符串(例如)并将其保留为文本,那么你就可以了:
function sanitizeText($str) {
$withSpecCharacters = htmlspecialchars($str);
$splitted_str = str_split($str);
$result = '';
foreach ($splitted_str as $letter){
if (strpos($withSpecCharacters, $letter) !== false) {
$result .= $letter;
}
}
return $result;
}
echo sanitizeText('ОРРииыфвсси ajvnsakjvnHB "&nvsp;\n" <script>alert()</script>');
//ОРРииыфвсси ajvnsakjvnHB &nvsp;\n scriptalert()/script
//No injections possible, all info at max keeped
function isolate($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
你应该使用 slugify 包而不是重新发明轮子;)
以下内容将用破折号替换空格。
$str = str_replace(' ', '-', $str);
然后以下语句将删除除字母数字字符和破折号之外的所有内容。 (没有空格,因为在上一步中我们已将它们替换为破折号。
// Char representation 0 - 9 A- Z a- z -
$str = preg_replace('/[^\x30-\x39\x41-\x5A\x61-\x7A\x2D]/', '', $str);
相当于
$str = preg_replace('/[^0-9A-Za-z-]+/', '', $str);
仅供参考:要从字符串中删除所有特殊字符,请使用
$str = preg_replace('/[^\x20-\x7E]/', '', $str);
\x20 是 Acsii 字符开头的空格的十六进制,\x7E 是波形符。根据维基百科https://en.wikipedia.org/wiki/ASCII#Printable_characters
仅供参考:查看十六进制列中的 20-7E 区间
可打印字符 代码 20hex 到 7Ehex 称为可打印字符,代表字母、数字、标点符号和一些杂项符号。总共有 95 个可打印字符。