Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中清理帖子标题,以便插入到数据库中进行SEO链接_Php_Regex_Seo - Fatal编程技术网

在php中清理帖子标题,以便插入到数据库中进行SEO链接

在php中清理帖子标题,以便插入到数据库中进行SEO链接,php,regex,seo,Php,Regex,Seo,我目前正在学习PHP,学习如何从用户输入的数据中获取一个字符串,并将其插入数据库,用作站点上帖子的链接。 我在函数中使用正则表达式来更改字符串,如下所示: function clean_url($string) { $string = preg_replace('/[^a-z0-9-]+/','-',strtolower($string)); // allows only characters from a-z and 0-9 and converts string to lower c

我目前正在学习PHP,学习如何从用户输入的数据中获取一个字符串,并将其插入数据库,用作站点上帖子的链接。 我在函数中使用正则表达式来更改字符串,如下所示:

function clean_url($string) {
    $string = preg_replace('/[^a-z0-9-]+/','-',strtolower($string)); // allows only characters from a-z and 0-9 and converts string to lower case
    $string = preg_replace('/-$/', '-', $string); // replace dash -
    $string = preg_replace('/--+/','',$string); // replaces double dashes with a single dash
    $string = preg_replace('/^-/', '', $string); // replace dash
    return $string;
}   
我想将所有正则表达式组合成一个有意义的正则表达式。牢记这些规则

  • 只允许使用a-z和0-9中的字符,即不允许使用除-之外的字符
  • 将字符串的所有-以及开头和结尾全部替换为零
  • 将所有双破折号替换为一个破折号
  • preg_replace()
    接受数组作为参数,因此一种方法是:

    $string = preg_replace(array('/[^a-z0-9-]+/','/-$/','/--+/','/^-/'),array('-','-','',''),strtolower($string));
    

    就我个人而言,我更喜欢使用每个表达式的原始函数,因为它使代码更具可读性。我也会考虑使用<代码> StryRePoT()/<代码>对于简单的替换< /p> 如果您不希望在字符串的末尾有任何代码> ->代码>字符,可以使用<代码> Times()/<代码> < /P> 对于双破折号替换,可以使用
    str\u replace()
    ;对于数字字符和字母字符,可以使用
    preg\u replace()


    保留所有不同的正则表达式语句似乎很模糊,我想将所有语句合并成一个正则表达式。通读一遍,有。@Xorifelse抱歉,我只是瞎了眼。@Maverick当替换值不同时,如何合并所有这些正则表达式?为什么不使用
    str_replace()
    ,将一个字符数组馈送到该函数中并完成。唯一有用的正则表达式是第一个正则表达式,其他正则表达式对我来说也很有意义。我不希望字符串中出现双破折号,也不希望url开头和结尾出现破折号。感谢您的回答,trim()不会删除字符串结尾或开头的破折号。它只删除空格。@Maverick直接从<代码>修剪-从字符串的开头和结尾去除空白(或其他字符)。我正在输入
    -
    ,因为
    trim()的第二个参数
    trim不会从我的字符串中删除破折号。好吧,我没有想到这一点。做得好。只是用了修剪('--hi there--),很酷的提示。
    function clean_url($string) {
      return trim(str_replace('--', '-', preg_replace('/[^a-z0-9-]+/','-', strtolower($string))), '-');
    }