Php 仅使用单连字符分隔符将字符串转换为slug
我想清理URL中的字符串,因此这是我基本上需要的:Php 仅使用单连字符分隔符将字符串转换为slug,php,regex,preg-replace,slug,sanitization,Php,Regex,Preg Replace,Slug,Sanitization,我想清理URL中的字符串,因此这是我基本上需要的: 除字母数字字符、空格和虚线外,所有内容都必须删除 空格应转换为破折号 例如 必须返回 this-is-the-url 首先剥离不需要的字符 $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); 然后更改取消排序的空间 $url = preg_replace('/\s/', '-', $new_string); 最后对其进行编码以备使用 $new_url = urlenco
this-is-the-url
首先剥离不需要的字符
$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
然后更改取消排序的空间
$url = preg_replace('/\s/', '-', $new_string);
最后对其进行编码以备使用
$new_url = urlencode($url);
这将在Unix shell中实现(我刚刚在MacOS上尝试过):
$tr-cs A-Za-z'-'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
来源:以前所有的asnwer都处理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
函数sanitizeText($str){
$withSpecCharacters=htmlspecialchars($str);
$splitted\u str=str\u split($str);
$result='';
foreach($拆分为$字母){
if(strpos($withSpecCharacters,$letter)!==false){
$result.=$letter;
}
}
返回$result;
}
echo sanitizeText('öППццфСцajvnsakjvnHB'&nvsp;\n“警报()”);
//БППццфСцajvnsakjvnHB&nvsp\n scriptalert()/script
//不可能注射,保留max的所有信息
以下内容将用破折号替换空格
$str = str_replace(' ', '-', $str);
// Char representation 0 - 9 A- Z a- z -
$str = preg_replace('/[^\x30-\x39\x41-\x5A\x61-\x7A\x2D]/', '', $str);
然后,下面的语句将删除除字母数字字符和虚线以外的所有内容。(没有空格,因为在上一步中,我们已将其替换为破折号
$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是平铺。与维基百科一样
仅供参考:查看间隔20-7E的六角柱
可打印字符
代码20hex到7Ehex,称为可打印字符,表示字母、数字、标点符号和一些杂项符号。总共有95个可打印字符。您应该使用Slagify软件包,而不是重新发明轮子;)
OP并没有明确描述一个slug的所有属性,但这正是我从意图中收集的 我对一个完美的、有效的、浓缩的slug的解释与这篇文章一致: 我发现之前发布的答案中没有一个能够始终如一地实现这一点(我甚至没有将问题的范围扩大到包含多字节字符)
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
我还准备了一个演示,突出了我认为其他答案不准确的地方。()
使用是一个很好的选择,因为有了它,您可以用一组规则轻松地处理复杂的情况。我添加了自定义规则来说明它是如何灵活的,以及如何最大限度地保留有意义的信息。请随意删除它们并添加您自己的规则
$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);
$strings=[
'这是--URL!',
“福尔摩斯与溜溜球”,
“我爱你”,
“如何赢得1000欧元?”,
欧元、美元和其他货币符号,
“这是我的梦想。”,
'Белите рози на София',
'പോണ്ടിച്ചേരി സൂര്യനു കീഴിൽ',
];
$rules='欧元';
[^0-9][01]? {'$'>'美元';'$'>'美元';
::空;
#怠慢
[^[:alnum:]&[:ascii:]+>'-';
::较低;
#修剪
[$]{'-'>&删除();
“-”}[$]>&删除();
规则;
$tsl=音译器::createFromRules($rules,音译器::FORWARD);
$results=数组映射(fn($s)=>$tsl->音译($s),$strings);
打印(结果);
不幸的是,PHP手册中关于ICU转换的内容是完全空白的,但是你可以找到关于它们的信息。嗨,jens,我对代码一无所知,这就是我需要帮助的地方。我只知道它应该使用preg_replace()但是我不知道正则表达式应该是什么。Thanksgreat thanks..只需一次编辑..我想在返回$z之前从开头和结尾删除破折号,以防它们存在。-1:读取SilentGhost的意图,而不是他/她编写的代码。这看起来是url安全的,这是以信息丢失为代价的。T为URL编码数据的正确方法是使用urlencode()(我看到它完成了示例中所示的转换,但不是atif089要求的转换)@symcbean urlecode不是我所需要的,因为我想消除符号而不是转换它们。所以这正是我想要的。@mario:1.它不做同样的处理;2.它是一个维护噩梦。下划线是另一个字符:
\uuu
是下划线,-
是连字符。还使用urlencode
on这样的字符串不会改变任何东西。您还忘记了第一个正则表达式中的hypen,\s
不等同于空格字符。我可以挑战任何人来证明我错了。不知道为什么我被否决了。可以在链接中找到演示,唯一的答案是无用的,特别是当它将被破坏时。您能详细说明一下这一点吗更多?最好在问题下方推荐该软件包作为注释。请在代码中添加更多信息,可能是如何使用或如何获得此答案。谢谢。
return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($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
$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);