麻烦在PHP中使用str_replace和preg_replace

时间:2011-01-05 05:15:43

标签: php regex string replace

我在php中遇到字符串操作问题。我正在编写一个函数,它带有一个字符串参数,其中的单词用“”或“_”分隔。我希望该函数删除所有非字母字符并返回用“ - ”分隔的单词。 这就是我到目前为止所做的:

function cleanCategoryForUrl($strCategory){
    $newCategory = str_replace('_', '-', $strCategory); //First replacement
    echo ($newCategory);
    $newCategory = str_replace(' ', '-', $newCategory); //Second replacement
    echo ($newCategory);
    $newCategory = preg_replace('/[^a-z-]/i', '', $strCategory); //Final replacement
    echo ($newCategory);
    return $newCategory;
}

第一次和第二次替换将使用“ - ”而不是“”或“_”分隔单词。最后的替换将使所有不是字母或“ - ”的字符变为红色。

但是当我测试代码时,我在最终替换后会得到意想不到的结果。

输入“Home_Health”后,我打印出来了:

Home-Health
Home-Health
HomeHealth

前两个输出符合预期,但第三个输出删除了“ - ”(不应该发生)。我怀疑我的正则表达式模式有问题,但是当我在http://gskinner.com/RegExr/上测试它时,这句话很好。我是新手使用正则表达式,无法弄清楚是什么问题。请帮忙

1 个答案:

答案 0 :(得分:2)

一切似乎都很好但只是你在preg_replace中传递的参数中的一个问题。 而不是传递$ newCategory,而是传递$ strCategory。

试试下面的一个,

function cleanCategoryForUrl($strCategory){
    $newCategory = str_replace('_', '-', $strCategory); //First replacement
    echo ($newCategory."<br/>");
    $newCategory = str_replace(' ', '-', $newCategory); //Second replacement
    echo ($newCategory."<br/>");
    $newCategory = preg_replace('/[^a-z-]/i', '', $newCategory); //Final replacement
    echo ($newCategory."<br/>");
    return $newCategory;
}

否则你可以使用这个。

function cleanCategoryForUrl($strCategory){
    $newCategory = preg_replace('/[_ ]/', '-', $strCategory); //Final replacement
    $newCategory = preg_replace('/[^a-z-]/i', '', $newCategory); //Final replacement
    echo ($newCategory."<br/>");
    return $newCategory;
}

希望这会有所帮助,

谢谢!

侯赛因。

相关问题