删除除字母和数字以外的所有字符,替换空格.PHP Regex


Removing all but letters and number, replacing spaces. PHP Regex

我正在准备一个字符串,用作目录列表。我正在处理用户输入的标题,需要删除除字母和数字外的所有标题,然后用_替换空格。。我已经能够用preg_replace接近这一点,但目前没有时间学习Regex的来龙去脉。

下面是字符串=This is a -string- that has /characters & other stuff! Let's filter it的一个示例。我拍摄的目的是:this_is_a_string_that_has_characters_other_stuff_lets_filter_it

我能够接近这个代码,但字符被删除的地方会留下后面的空格。结果是两双,这是可以接受的,但不是我想要的。

如有任何帮助,我们将不胜感激。这是我的尝试:

<?php
$string = " This is a -string- that has /characters & other stuff! Let's filter it?";
$cleansedstring = trim($string);
$cleansedstring = strtolower($cleansedstring);
$cleansedstring = preg_replace('/[^ 'w]+/', '', $cleansedstring);
$cleansedstring = preg_replace('['s]', '_', $cleansedstring);
echo $cleansedstring;
?>

更新这是我从这里的一些建议中发现的,看起来很干净,并输出了我拍摄的字符串。。改进建议?

$string = " This is a -string- _that has /characters & other stuff! Let's filter it?23";
$cleansedstring = trim($string);
$cleansedstring = strtolower($cleansedstring);
$cleansedstring = preg_replace('/[^ 'pL 'pN]/', '', $cleansedstring);
$cleansedstring = preg_replace('['s+]', '_', $cleansedstring);
echo $cleansedstring;

用于删除不需要的字符的正则表达式不应该有+,而检查空格的正则表达式后面需要+

这也有效:

$s = "This is a -string- that has /characters & other stuff!    Let's filter it";
echo "ORIG: [{$s}]<br />";
$s = preg_replace("/[^0-9a-zA-Z's]/","",$s);
$s = preg_replace("/'s['s]+/"," ",$s);
$s = preg_replace("/'s/","_",$s);
$s = strtolower($s);
echo "NEW: [{$s}]<br />";
// output is
// ORIG: [This is a -string- that has /characters & other stuff! Let's filter it]
// NEW: [this_is_a_string_that_has_characters_other_stuff_lets_filter_it]

试试这个:

<?php
$string = " This is a -string- that has /characters & & other stuff! Let's filter it?";
$cleanstring = strtolower(trim(preg_replace('#'W+#', '_', $string), '_'));

这里有一个我稍微修改过的旧函数,使用下划线:

public function make_url_friendly($string)
{
    $string = trim($string);
    // weird chars to nothing
    $string = preg_replace('/('W'B)/', '',  $string);
    // whitespaces to underscore
    $string = preg_replace('/['W]+/',  '_', $string);
    // dash to underscore
    $string = str_replace('-', '_', $string);
    // make it all lowercase
    $string = strtolower($string);
    return $string; 
}

这应该可以满足的需要