24

我想将一个字符串清理到一个 URL 中,所以这就是我基本上需要的:

  1. 除字母数字字符和空格和虚线外,所有内容都必须删除。
  2. 空格应转换为破折号。

例如。

This, is the URL!

必须返回

this-is-the-url
4

10 回答 10

51
function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');
}
于 2010-06-11T11:14:21.360 回答
4

首先去除不需要的字符

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

然后更改 unsercores 的空格

$url = preg_replace('/\s/', '-', $new_string);

最后对其进行编码以备使用

$new_url = urlencode($url);
于 2010-06-11T11:20:45.603 回答
1

这将在 Unix shell 中完成(我刚刚在我的 MacOS 上尝试过):

$ tr -cs A-Za-z '-' < infile.txt > outfile.txt

我从一篇关于更多壳,更少鸡蛋的博客文章中得到了这个想法

于 2015-12-06T17:41:43.080 回答
1

试试这个

 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

来源:https ://stackoverflow.com/a/14114419/2439715

于 2016-04-07T07:35:39.877 回答
1

OP 并没有明确描述蛞蝓的所有属性,但这是我从意图中收集到的。

我对完美、有效、浓缩的 slug 的解释与这篇文章一致:https ://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we%20can% 20summarise%20the,or%20end%20with%20a%20hyphen

我发现之前发布的答案都没有始终如一地实现这一目标(而且我什至没有将问题的范围扩大到包括多字节字符)。

  1. 将所有字符转换为小写
  2. 将一个或多个非字母数字字符的所有序列替换为单个连字符。
  3. 从字符串中修剪前导和尾随连字符。

我推荐以下不打扰声明一次性变量的单行代码:

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 &amp; 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
于 2020-12-13T21:36:48.840 回答
0

以前所有的 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
于 2017-07-04T18:28:21.343 回答
0
    function isolate($data) {
        
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        
        return $data;
    }
于 2020-07-16T00:16:15.087 回答
0

使用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);

演示

不幸的是,关于 ICU 转换的 PHP 手册完全是空的,但您可以在此处找到有关它们的信息。

于 2021-06-02T23:03:02.930 回答
-1

以下将用破折号替换空格。

$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 个可打印字符。

于 2019-09-20T10:09:14.883 回答
-1

你应该使用 slugify 包而不是重新发明轮子;)

https://github.com/cocur/slugify

于 2020-03-26T13:58:40.143 回答