删除所有字母和数字,替换空格。 PHP正则表达式

时间:2012-02-20 19:35:20

标签: php regex preg-replace

我正在尝试准备一个字符串用作目录列表。我正在处理用户输入的标题,需要删除除字母和数字之外的所有标题,然后用_替换空格。我已经能够与preg_replace稍微接近,但没有时间了解目前正则表达式的来龙去脉。

以下是string = 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;

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

这也有效:

$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]

答案 2 :(得分:0)

这是我的一个旧功能 - 略微修改为使用下划线:

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; 
}

这应该做你需要的事情

答案 3 :(得分:0)

试试这个:

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